Is it possible build an array of SQL commands to query the DB? What I have is three tables, each have columns with amounts due. Would like to select anything that is due and display on screen so it can be invoiced (preferably in a table) and each row with it's respective customers dues.
I can select everything that is due using UNION ALL between the three tables, however I cant figure out how to list them by ID in the table row.
Below is what I have so far. At this pace I'll have to run each query separately and list them in three separate lists. Suggestions?
<table>
<tr>
<th> ID</th>
<th> Cost 1</th>
<th> Cost 2</th>
<th> Cost 3</th>
</tr>
<?php
$list1 = "SELECT ID, Cost FROM Table1 WHERE Invoiced IS NULL;";
//$list2 = "SELECT ID, Price2 FROM Table2 WHERE Expiration BETWEEN '$curDate' AND '$maxDate';";
//$list3 = "SELECT ID, Price3 FROM Table3 WHERE Expiration BETWEEN '$curDate' AND '$maxDate'";
$result = mysql_query($list1, $link) or die(mysql_error());
$num_rows = mysql_num_rows($result);
$num_fields = mysql_num_fields($result);
for ($i=0; $i<$num_rows; $i++) {
for ($j=0; $j<$num_fields; $j++) {
$invoice[$i][mysql_fieldname($result,$j)] = mysql_result($result,$i,mysql_field_name($result,$j));
}
}
//eventually the order it should be listed on screen
for($i=0; $i<count($invoice); $i++) {
echo "<tr><td>".$invoice[$i]["ID"]."</td>
<td>".$invoice[$i]["Cost"]."</td>
<td>".$invoice[$i]["Price2"]."</td>
<td>".$invoice[$i]["Price3"]."</td></tr>";
}
?>
</table>
Edit after comment:
Query being passed and returning syntax error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'all LEFT JOIN table1 ON all.ID = table1.ID LEFT JOIN t' at line 7:
$query = "
SELECT all.ID, table1.Cost1, table2.Price2, tabl3.Price3
FROM
(SELECT ID, Cost1 FROM table1 WHERE Invoiced IS NULL
UNION
SELECT ID, Price2 FROM table2 WHERE Expiration BETWEEN '$curDate' AND '$maxDate'
UNION
SELECT ID, Price3 FROM table3 WHERE Expiration BETWEEN '$curDate' AND '$maxDate') AS all
LEFT JOIN table1 ON all.ID = table1.ID
LEFT JOIN table2 ON all.ID = table2.ID
LEFT JOIN table3 ON all.ID = table3.ID
";
From the table header you have created above which places the three Cost columns in a single row by ID, you seem to imply that you want to to JOIN the three tables together on their ID. I am using a LEFT JOIN here, to be sure that all rows from Table1 are present, even if there is no corresponding row in either of the other two tables.
SELECT
Table1.ID,
Table1.Cost as Cost1,
Table2.Price2 AS Cost2,
Table3.Price3 AS Cost3
FROM
Table1
LEFT JOIN Table2 ON Table1.ID = Table2.ID
LEFT JOIN Table3 ON Table1.ID = Table3.ID
WHERE
Table1.Invoiced IS NULL
AND Table2.Expiration BETWEEN '$curDate' AND '$maxDate'
AND Table3.Expiration BETWEEN '$curDate' AND '$maxDate'
Update after comments:
In the case that Table2 may have an ID not held in Table1 or Table3, for example (where Table1.ID can't be considered authoritative), you can get the total set of DISTINCT ID from all 3 tables via a UNION and use that to join against:
SELECT
allID.ID,
Table1.Cost1,
Table2.Price2 AS Cost2,
Table2.Price3 AS Cost3
FROM
/* Subquery gets a distinct set of IDs from all tables via UNION
so the outer query has a complete list to join against the other tables */
(
SELECT ID FROM Table1
UNION SELECT ID FROM Table2
UNION SELECT ID FROM Table3
) allID
LEFT JOIN Table1 ON allID.ID = Table1.ID
LEFT JOIN Table2 ON allID.ID = Table2.ID
LEFT JOIN Table3 ON allID.ID = Table3.ID
/* Sorry, forgot the WHERE clause here */
WHERE
Table1.Invoiced IS NULL
AND Table2.Expiration BETWEEN '$curDate' AND '$maxDate'
AND Table3.Expiration BETWEEN '$curDate' AND '$maxDate'
Note that the existence of three tables with nearly identical column structures in a one-to-one relationship probably implies a design problem. You might consider combining these into a single table.
A further note about the PHP:
In PHP, we almost never use an incremental for loop for iteration as you would in C/C++. Instead, we typically make use of a foreach or when fetching rows from a query, a while loop.
// Fetch in a while loop
$invoice = array();
// $result is your query resource as you already have it...
while ($row = mysql_fetch_assoc($result)) {
// Accumulate rows into $invoice array
$invoice[] = $row;
}
// Then loop over the array:
foreach ($invoice as $inv) {
echo "<tr>
<td>{$inv['ID']}</td>
<td>{$inv['Cost1']}</td>
<td>{$inv['Cost2']}</td>
<td>{$inv['Cost3']}</td>
</tr>";
}
Final update:
Yes, the WHERE clause will restrict for all conditions met. If you need to limit them individually, you must do so in subqueries which are then joined together, using the same UNION subquery to get the distinct set of ID
SELECT
allID.ID,
T1.Cost1,
T2.Price2 AS Cost2,
T3.Price3 AS Cost3
FROM
(
SELECT ID FROM Table1
UNION SELECT ID FROM Table2
UNION SELECT ID FROM Table3
) allID
LEFT JOIN (SELECT ID, Cost AS Cost1 FROM Table1 WHERE Invoiced IS NULL) T1 ON allID.ID = T1.ID
LEFT JOIN (SELECT ID, Price2 AS Cost2 FROM Table2 WHERE Expiration BETWEEN '$curDate' AND '$maxDate') T2 ON allID.ID = T2.ID
LEFT JOIN (SELECT ID, Price3 AS Cost3 FROM Table3 WHERE Expiration BETWEEN '$curDate' AND '$maxDate') T3 ON allID.ID = T3.ID
Related
I know this involves JOINS but I can't seem to find a working solution to what I'm trying to do.
I have 2 custom tables :
table1 | table2
---------------------
id id
uid uid
track_id track_id
date date
art active
info
blah
blah2
First I want to select everything WHERE uid=55 AND active=1 from table2 :
$tracks = $wpdb->get_results( "SELECT * FROM table2 WHERE uid = 55 AND active = 1");
And then match the track_id from table2 with results from table1 so I can traverse the table1 data.
I know I can do it like this :
foreach( $tracks as $track ) {
$this_track = $track->track_id;
$results = $wpdb->get_results( "SELECT * FROM table1 WHERE track_id = $this_track");
// Do stuff here
}
But this is the part where it gets tricky...
I then want to ORDER the $results from table1 by date DESC from table2
And this is where I'm lost...
Effectively I want (pseudo code) :
$results = $wpdb->get_results( "SELECT * FROM table1 WHERE track_id = $this_track" ORDER BY date DESC FROM table2);
As well as that last bit, I know I can do this entire routine with JOINS to keep this all in one query and make it way more efficient but I just don't know how.
So just to be clear, my overall routine should be like this :
Get all instances of track_id from table2 where user_id=55 and active=1, then use those results to match the track_id to every result in table1 with the same track_id and then sort the results by date back over from table2
Psuedo code, I know it contains nonsense :
$finalresults = $wpdb->get_results( "SELECT * FROM table2 where uid=55 AND active=1 THEN SELECT * FROM table1 WHERE track_id = "the track_id from the first query" THEN ORDER BY date DESC FROM table2);
Try with this query
SELECT t1.* ,t2.date AS t2date, t2.active FROM table2 AS t2 INNER JOIN table1 AS t1 ON (t1.track_id = t2.track_id) WHERE t2.uid=55 AND t2.active=1 ORDER BY t2.date DESC;
Edit: Explanation of what this query is doing. and inverted the order of the tables retrieved in the query (this don't affect the final datatset, i did this to make to follow the logic of the explanation.
1.- Begin with retrieving all rows from table2 (theres is no specific reason because i used table2 over table1, I'm only following an logical order), using the criteria that you specified iud=55 and active=1
SELECT * FROM table2 WHERE uid=55 AND active=1;
2.- but as you said you need to expand the data retrieved in table2 with some information in table1, that's exactly what it is the directive JOIN made, and we are using INNER JOIN because this type of JOIN will show rows ONLY if data for the uid=55 is present on table1, if there is NO data for the uid=55 present on both TABLES then mysql wil show empty the recordset (0 Rows selected).
in the ON(...) part I specify which criteria mysql will use to compara both tables for match in this case will compare that track_id on table2 it is the same that the specified on table1, if this codition is met then mysql considers it as a match.
anly for convenience and because i'm adding a Second table i gave an Alias to each one t1 and t2.
then the query now seems like this
SELECT * FROM table2 AS t2 INNER JOIN table1 AS t1 ON(t1.track.id = t2.track_id) WHERE t2.uid=55 AND t2.active=1;
3.- but then raise a problem, both tables has rows with the same field names, and this is something that DBMS don't like in their queries, to avoid this situation in the query i only show the fields (id, uid and track_id) from one table in this case t1 (t1.*) and only show the fields that doesn't have this problem from t2 (t2.date AS t2date, t2.active). in this way mysql won't throw any error.
SELECT t1.* ,t2.date AS t2date, t2.active FROM table2 AS t2 INNER JOIN table1 AS t1 ON (t1.track_id = t2.track_id) WHERE t2.uid=55 AND t2.active=1;
4.- for the final step i specify to mysql that i want all found rows ordered descent by a field in the table2;
ORDER BY t2.date DESC;
then this criteria will be applied to the whole selected rows. and the final query has this form.
SELECT t1.* ,t2.date AS t2date, t2.active FROM table2 AS t2 INNER JOIN table1 AS t1 ON (t1.track_id = t2.track_id) WHERE t2.uid=55 AND t2.active=1 ORDER BY t2.date DESC;
if is not completely clear you can ask ...
I am new to php & mysql and I'm trying to make a script that gets the distance walked with the player's name. I can get the player's walked distance with his id, but the value for the player_id is in a different table.
It looks like this:
Table1: player_id | foot (walked distance)
Table2: name | player_id
So I want to use the name by the player_id in my table.
Code
You require a simple join.
SELECT Table1.foot, Table2.name
FROM Table1
INNER JOIN Table2
ON Table1.player_id = Table2.player_id;
You just need to join both these table.
Just try this code:
$query = "SELECT T1.*, T2.name
FROM table1 T1
LEFT JOIN table2 T2 ON T1.player_id = T2.player_id
ORDER BY T2.name ASC";
For more details of JOIN: Link
Let me know for more help.
You can use
$query = "select t1.player_id, t2.name, t1.foot
from table1 t1
join table2 t2 on t1.player_id = t2.player_id"
If you want to order the player names in alphabetical order then you can additionally use order by clause
$query = "select t1.player_id, t2.name, t1.foot
from table1 t1
join table2 t2 on t1.player_id = t2.player_id
order by t2.name"
Use left join in mysql.
Suppose if you have two tables use this
SELECT T1.*,T2.walked distance
FROM table1 T1
LEFT JOIN table2 T2
ON T1.id=T2.player_id;
Click Here For more example
I have a select query and an insert query as follows:
$select_query = mysql_query("SELECT trees, animals FROM Table1 WHERE gardens > '10000'", $mysql_connection);
while ($row = mysql_fetch_array($select_query)) {
$trees = $row['trees'];
$animals = $row['animals'];
$names = ?????????? // in order to get the names, a select query should go through Table2 and Table4
//and finally get the assigned names from Table3. Please see the schematic picture of tables.
$insert_query = mysql_query("INSERT INTO table6 (new_trees, new_animals, new_name) VALUES ('$trees', '$animals', '$names')", $mysql_connection); }
I want to select and insert the $trees, $animals and $names into another table. There is no problem with $trees and $animals variables, but I do not know how to select the data for $names. As it is seen in the schematic picture of tables, Table1.id=Table2.reference and Table2.first_id gets values from Table4.id.
Then, Table4.second_id gets values from Table3.id and finally Table3.name must be selected in order to satisfy the $names variable in above-mentioned $insert_query. Sorry if I did not explain the problem more clearly. Could you please review the picture and let me know your solution?
Lookup the JOIN clauses:
SELECT
t1.id, t1.trees, t1.animals, t3.name
FROM table1 AS t1
LEFT JOIN table2 AS t2
ON t2.reference = t1.id
LEFT JOIN table4 AS t4
ON t2.first_id = t4.id
LEFT JOIN table3 AS t3
ON t4.second_id = t3.id
WHERE // Your select conditions
can you help me
$sql="select * from table1 where id='1,2,3,4'";
{
$sql2="select distinct column1 from table2 where column2='".$row['id']."' and left(date,10) BETWEEN '".$date_from."' AND '".$date_to."'";
}
I need to sort $sql by number of rows descending for $sql2 by id
If I understand you correctly, you want the results from $sql ordered by number of rows found by $sql2 for each row in $sql. This join should do that, it joins table2 and orders by the count, descending.
SELECT t1.id
FROM table1 t1
LEFT JOIN table2 t2
ON t1.id=t2.column2
WHERE id IN (1,2,3,4) -- should it really be = '1,2,3,4'?
AND LEFT(date,10) BETWEEN '2013-01-01' AND '2013-12-31'
GROUP BY t1.id
ORDER BY COUNT(DISTINCT t2.column1) DESC
An SQLfiddle to test with.
I need to select all (*) the rows from table1, table2, table3.. but I need to select the MIN and MAX price from table 2 within this INNER JOIN. I've read up on how to do this, but how do I do this within an INNER JOIN, and how do I display it in a PHP variable.
Initial Problem: How do I display the min and max values once I pull them.. (e.g $Result['MinPrice'], $Result['MaxPrice']).
Here's my query:
$Query = mysql_query("
SELECT *
FROM table1
INNER JOIN table2 ON table1.UserID = table2.UserID
INNER JOIN tables3 ON table2.DeviceID = table3.DeviceID
WHERE table2.DeviceID = '$GetDeviceID'
");
Here is the tables structure:
table1 = usersinfo
UserID UserFirstName UserLastName UserDisplayName
1 John Doe John D.
table2 = listings
ListingID UserID DeviceID
11 1 2
table3 = devices
DeviceID
2
If you really want to do what you're asking in this way you can use the query that is displayed below. This does, however, return a lot of duplicate rows if you have multiple rows returned when querying. Try it and see if it works.
$Query = mysql_query("
SELECT table1.*, table2.*, table3.*,
MIN(table2.price) as minny,
MAX(table2.price) as maxxy
FROM table1
INNER JOIN table2 ON table1.UserID = table2.UserID
INNER JOIN tables3 ON table1.DeviceID = table3.DeviceID
WHERE table1.DeviceID = '$Something'
GROUP BY table2.ListingAskingPrice
");
Then get this value by doing $result['minny'] and $result['maxxy']