If I have a list of ID's that I have selected from a statement
SELECT id FROM myTable WHERE name = 'TEST'
This would return just the ids (1001, 1002, 1003, etc...) Then I want to perform another SELECT statement to retrieve all the titles for all those ids.
SELECT title FROM myTable2 WHERE id = XXXX
the id in table2 is the foreign key of table2. id in myTable is the Primary Key. How can I go about retrieving all the titles from those ids. I was thinking about storing all the results of the first select statement in an array, and then using a while loop to iterate through the list and return each result into another array, but my fear is that when the database gets big if it has to return 1000 rows that could be some bad overhead. So in PHP or SQL what is the best way to perform this?
You can use a subquery:
SELECT title
FROM myTable2
WHERE id IN (
SELECT id
FROM myTable
WHERE name = 'TEST'
)
Another way to do it would to be use a JOIN, to avoid the sub-query:
SELECT title
FROM myTable2
LEFT JOIN myTable
ON myTable.id = myTable2.id
WHERE myTable.name = 'TEST'
You should just be able to select them at the same time.
SELECT a.id, b.title
FROM myTable a, myTable2 b
WHERE a.name = 'TEST' AND b.id = a.id;
to select both:
SELECT id, title FROM mytable WHERE name="TEST"
or to select the whole row
SELECT * FROM mytable WHERE name="TEST"
if its two tables you are selecting from:
SELECT id, title FROM mytable A JOIN mytable2 B USING (id)
Related
First post, be gentle! My SQL knowledge is average, at best.
I have 2 tables with no direct relationship to each other.
TableA ("CustomerWishList") with columns "bookID", other-book-data,
etc etc etc
TableB ("CustomerOwned") with columns - "bookID", other-book-data, etc etc etc
A book could be in one, both, or none of those tables.
I need to create SQL statement that counts the number of "bookID='data'" occurrences in either TableA or TableB.
So far using PHP I'm searching TableA "bookID" column first, and then if nothing found, searching TableB "bookID" column next ... it works, but is inefficient, and am convinced there must be a better way.
JOIN statements don't seem to apply here? - I could be wrong.
UPDATED
Psuedo PHP code I'm currently using:
$total=SELECT COUNT(*) FROM CustomerWishList WHERE BOOKID=1234
if ($total==0) {
$total2=SELECT COUNT(*) FROM CustomerOwned WHERE BOOKID=1234
}
return $total2;
Below query would give you count of book ids which are only in table A:
SELECT count(1) as `count`
FROM tableA
WHERE NOT EXISTS
(SELECT bookID FROM tableB WHERE bookID = tableA.bookID);
Similarly, following query would give you count of book ids which are only in table B:
SELECT count(1) as `count`
FROM tableB
WHERE NOT EXISTS
(SELECT bookID FROM tableA WHERE bookID = tableB.bookID);
Now, if you want to add these two then you can use the following query:
SELECT `a.count` + `b.count`
FROM (
SELECT count(1) as `count`
FROM tableA
WHERE NOT EXISTS
(SELECT bookID FROM tableB WHERE bookID = tableA.bookID)
) a,
(
SELECT count(1) as `count`
FROM tableB
WHERE NOT EXISTS
(SELECT bookID FROM tableA WHERE bookID = tableB.bookID);
) b;
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 have the below table (in picture) which is kind of inventory table and shows how many items comes in and how many goes out from stock, and item_id is the foreign key from another table.
I want to select those records that has no out from the stock, in other word i want to select those records which are highlighted in green (in the picture).
Thanks.
Sorry for poor English
The Table
Try this:
Select * from `table` where id in (select id from `table`group by id having sum(out)=0);
for deleting those values use:
delete t1
from `your_table` as t1
join (select item_id from `your_table`group by item_id having sum(item_out)=0) t2 on t1.item_id = t2.item_id
Try this query.
SELECT * FROM 'table_name' where out=0;
You need to join the table to itself: SELECT t.* FROM <your_table> AS t LEFT JOIN <your_table> AS t1 ON t.item_id=t1.item_id WHERE t1.out>0 AND t1.item_id IS NULL
$result = mysql_query( "SELECT id FROM table1 UNION ALL SELECT id FROM table2;" , $link);
while($end = mysql_fetch_assoc($result))
{
echo $end['id']; // how separate and specify output is frow which table ?
}
i have two table (phpmyadmin), and i want to search in both of them with 1qeury, then i'm use UNION to combine, now i want to seprating output and specify from what table is evry result (row)? tnx
Add an extra column that indicates which table it is:
SELECT "table1" which, id FROM table1
UNION ALL
SELECT "table2" which, id FROM table2
Now you can use $end['which'] to know which table each row came from.
which isn't a column in the table itself. It's an alias for the literal string that's just in the query.
To get the results ordered alternating between the tables, you can do:
SELECT *
FROM (
SELECT "table1" which, id FROM table1
UNION ALL
SELECT "table2" which, id FROM table2
) x
ORDER BY id, which
Use aliases:
$result = mysql_query( "SELECT id as table1_id FROM table1
UNION ALL SELECT id FROM table2;" , $link);
And then:
echo $end['table1_id'];
echo $end['id'];
Let's say I have to MySQL tables like this.
TBL_1
ID - NAME - DESCRIPTION
1 foo very nice
TBL_2
ID - PRICE - CATEGORY - QUANTITY
1 10 a 5
If I was to set up a PDO instance like so....
<?php
$handler = new PDO("XXXX;XXXXX","XXX","XXX");
$query = $handler->query('SELECT * FROM TBL_1');
while($r = $query->fetch(PDO::FETCH_OBJ)) {
echo $r->id;
echo $r->name;
echo $r->description;
//echo $r->price;
//echo $r->category;
//echo $r->quantity;
}
How can I access price, category, quantity where the ID's, in both tables are equal to each other?
So for example, it would come out like this.
1 foo very nice 10 a 5
You might use JOIN:
SELECT name, description, price, category, quantity
FROM TBL_1
JOIN TBL_2
USING (id)
Hope it helps.
Assuming the ID columns contain the same values (i.e. a foreign key constrait exists because the values represent the same entity), you'll want to execute a query with an INNER JOIN on that column. By default with an INNER JOIN, if the requested value (for instance a WHERE 'ID' = 3 clause) does not exist in either table, no results will be returned. Try the following:
SELECT *
FROM `TBL_1` AS `t1`
INNER JOIN `TBL_2` AS `t2` ON `t1`.`ID` = `t2`.`ID`;
You just do an INNER JOIN on the table where on each table the id is equal.
SELECT * FROM TBL_1 INNER JOIN TBL_2 ON TBL_1.ID=TBL_2.ID;