MySQL: Selecting from multiple tables that have no relationship - php

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;

Related

Getting multi count from two table and save it in one variable in PHP Codeigniter

I have two tables and I need to get the count of these tables for a condition?
table 1: "tbl_comment" table 2: "tbl_group_comment"
both have some common columns which are login_id of the user,
this is the query:
$param="(SELECT COUNT(*) FROM tbl_comment as t2 WHERE login_id=1) as commentCount, (SELECT COUNT(*) FROM tbl_group_comment as t3 WHERE login_id=1) as commentCount";
$table="`tbl_comment` t2 join `tbl_group_comment`";
$save['value']=$this->Common_model->common_join($param,$table);
this one is not working but if I am changing the second commentCount and keep it as commentCount1 it will give me the value of each table, I want to get the sum of both counts?
is there any specific clause for this matter?
Try this:
select sum(comment_count + group_count) from
((SELECT COUNT(*) as comment_count FROM tbl_comment WHERE login_id=1) A,
(SELECT COUNT(*) as group_count FROM tbl_group_comment WHERE login_id=1)B
);

Getting data from one table based on results of another SQL PHP

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 ...

Selecting specific rows from table

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

PHP / MYSQL Statement so select Max Sum of Join

I have Problems with a select statement, as a little help here are the important columns:
Table1
ID NAME
TABLE 2
ID U_ID COUNTER
The ID of Table 1 Matches the U_ID of Table 2. Table 2 contains many entries for the same u_id.
What I want to do is to get the Name of the "user" (table 1) who has in sum the max. counter.
What I got since now is the join of the tables (Where clause depends on other rows which are not important for the problem).
Can anyone help me on this issue?
So what you need is an aggregate of an aggregate (max of sum of column). The easiest will be to create a view providing the sum and u_id end then select the max of it:
create view table2sums
as
select u_id, sum(counter) as total
from table2
group by u_id;
and then
select t1.name
from table1 t1, table2sums t2
where t1.id = t2.u_id
and t2.total >= all (
select total
from table2sums
)
In this special case you can also do it directly:
select t1.name
from table1 t1, table2 t2
where t1.id = t2.u_id
group by t1.name
having sum(t2.counter) >= all (
select sum(counter)
from table2
group by t2.u_id
)
NOTE: The other proposed solutions will show a better performance. My solution only selects the name (which is what you said you wanted) and works in any RDBMS.
There exist RDBMS without the LIMIT possibility.
In the end, I'd say: regard my solution as educational, the others as practical
SELECT name,
SUM(counter) as counter
FROM table1
JOIN table2
ON table1.id = table2.u_id
GROUP BY u_id
ORDER BY counter DESC
LIMIT 1
You can try this:
SELECT name, SUM(counter) as total_counter
FROM table1
JOIN table2
ON table1.id = table2.u_id
GROUP BY u_id
ORDER BY total_counter DESC
LIMIT 1
Working Demo: http://sqlfiddle.com/#!2/45419/4

PHP/SQL Statement repeating a query

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)

Categories