compare two table with row and column - php

I have two tables table1 and table2
In table1 fieldname is cert_no and in table2 fieldname is cer1,cert2,cert3,cert4,cert5
The value which was not in table2 (cer1,cert2,cert3,cert4,cert5) alone want to display
If both table has same value only transfile_file want to display
SELECT *
FROM table1
WHERE folio = '123456'
AND cm_flag !='X'
AND certificate_no NOT IN
(SELECT CONCAT(certno1,certno2,certno3,certno4,certno5,certno6,certno7,certno8,certno9,certno10)
FROM table2
WHERE tofolio = '123456'
)

If you use for example Microsoft SQL Server there is a function EXCEPT that return the different rows between 2 tables with the same fileds (same name, same types and same positions). In Oracle there is MINUS operation that is the same of EXCEPT.
In MySQL does not implement a EXCEPT or MINUS operation which is a unfortunate as it can allow for better execution plans in some cases than the alternatives.
This is a valid aternative and more performing than use NOT IN operation: realize a join is the best solution in SQL.
enter code here
SELECT a.*
FROM table1 as a
LEFT JOIN table2 as b
ON a.tofolio = b.tofolio
WHERE b.tofolio IS NULL

Try:
SELECT * FROM table1 WHERE folio = '123456' AND cm_flag !='X' AND certificate_no NOT IN (SELECT CONCAT(certno1,',',certno2,',',certno3,',',certno4,',',certno5,',',certno6,',',certno7,',',certno8,',',certno9,',',certno10) FROM table2 WHERE tofolio = '123456')

Related

sql query : perform a where in if condition

i've a situation like the following :
i've a long query that join a table
all the columns in joined tabled contain a column 'name'. in this table there are two names 'A' and 'B' (but can be C,D......Z, i don't know how many names we can have) and both of them have multiple rows, so i've n rows with name A and n rows with name B
sometimes, based on the user input, i need to join the entire table (with all the names) BUT only put some condition where the name is 'A' (for example).
so :
joint table myTable (it will take all the results A,B,C...)
but if the name = 'A'
then A.priority = A.userInput
(for B,C... get them without additional conditions)
so, is there a solutions for this or i need to do multiple calls to the database ?
Thanks.
I would use UNION ALL clause for this
SELECT *
FROM TABLE1 T1
JOIN TABLE2 T2
ON T1.somecolumn = T2.somecolumn
WHERE T2.name <> 'A'
UNION ALL
SELECT *
FROM TABLE1 T1
JOIN TABLE2 T2
ON T1.somecolumn = T2.somecolumn
WHERE T2.name = 'A' AND some condition

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

select values with same cloumn a but different column b

I am using phpmyadmin database.
I have a table with columns 'admitno' and 'name' . I want to select values with same Admit No but different name and display those admitno along with all names against it.
I have tried code like
SELECT Admitno, Name
FROM table1 t1
WHERE EXISTS
(
SELECT 1 FROM table1 t2
WHERE t2.Admitno= t1.Admitno
AND t2.Name<> t1.Name
)
But not working in my case. Any suggestion please
You have to use self join and then filter data on the conditions that the two alias of table have same Admitno but different name
SELECT * from table1 a join table1 b where a.Admitno = b.Admitno and a.Name!=b.Name

select * from two tables with different # of columns

How would I select different columns from two different tables, such as:
SELECT username, email FROM `table1`
UNION
SELECT * FROM `table2` WHERE username = 'user1';
I'm getting an error "#1222 - The used SELECT statements have a different number of columns". From what I understand UNION will not work,
Is there a way to accomplish this, since I would need unequal number of columns and rows and there are no mutual/similar entries in the two tables (i.e. user1 is not listed in table1)?
Can this not be done in one query?
thank you!
You can fake the missing columns using an alias - e.g.
SELECT username, email, '' as name FROM `table1`
UNION
SELECT username, email, name FROM `table2`
WHERE username = 'user1';
where name is in table2, but not in table1
Unless you're confusing UNIONS with JOINS:
SELECT table1.*, table2.* FROM
table1 INNER JOIN table2
ON table1.username = table2.username
this would merge both tables, so you get all the columns on the same row.
If there's no mutual or similar entries in the two tables, these should be two different select statements.
SELECT username, email FROM `table1`;
SELECT * FROM `table2` WHERE username = 'user1';
What's your motivation for doing otherwise?
Are the entries in table2 related to table1? Would a join be more appropriate?
SELECT t1.username, t1.email, t2.*
FROM table1 t1
JOIN table2 t2 ON t1.username = t2.username
WHERE t1.username = 'user1';
In the table with less columns, try
SELECT *, 0 as col1, 0 as col2, ...
etc in order to make them the same number of columns.

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