sql query : perform a where in if condition - php

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

Related

SQL query - Can I query 2 tables that both have an ID field and retrieve both fields?

I have two tables. Both have fields called "ID".
Table 1 has "ID", "Title", "Shift"
Table 2 has "ID", "Table1ID", "Details"
I would like to query Table 2 and retrieve all it's details based on an "ID" value but also get the values from Table 1 that relate to the "Table1ID" value.
I've tried this...
SELECT * FROM Table2 a, Table1 b WHERE a.TableID = b.ID
This works but only retrieves one tables "ID" field.
I've been playing about with UNION ALL but can't get it to work.
Any ideas?
Thanks
Yes, you can add an alias:
SELECT a.ID AID, a.Title, a.Shift, b.ID BID, b.TableID, b.Details
FROM Table2 a, Table1 b
WHERE a.TableID = b.ID
The above will return ID from table A and B as AID and BID in the result.
Is there a way to get the SELECT to get all the fields (without
explicitly writing them) and still alias a specific field?
yes its possible but is considered harmful
This is how you would do id
SELECT Table1.*,Table2.* from table1 inner join Table2 on Table1.ID = Table2.Table1ID;
Why I'm saying its harmful see here : Why is SELECT * considered harmful?
Proper select should be :
SELECT Table1.ID,Table1.Title,Table1.Shift,Table2.ID.Table2.Table1ID,Table2.Details.* from table1 inner join Table2 on Table1.ID = Table2.Table1ID;

compare two table with row and column

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')

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

Using Two Tables with the WHERE clause from two databases

I have two tables from two different databases. TableA (database-1) and TableB (database-2). TableA has three attributes (student_id, semester, account_status) and TableB has two attributes (student_id, assesor_status). How do i connect to both databases at the same time and get to pull out the data from both tables and have it counted to giving me the sum of all student_id which have an account_status value 'ACTIVE' and semeter value '6' and assesor_status with value 'PENDING'
This is what i did but im failing to connect to both databases at the same time.
SELECT (COUNT)TableA.student_id
FROM TableA, TableB
WHERE semester = '6'
AND account_status = 'ACTIVE'
AND assesor_status = 'PENDING';
If you are using one connection to access both DBs you could
SELECT COUNT(a.student_id)
FROM DBA.TableA a
INNER JOIN DBB.TableB b ON a.student_id = b.student_id
WHERE a.account_status = 'AVTIVE'
AND a.semesteer = '6'
AND b.assesor_status = 'PENDING'
Otherwise you you could use two queries
SELECT b.student_id
FROM TableA b
WHERE b.assesor_status = 'PENDING'
Then use result with IN
SELECT COUNT(a.student_id)
FROM TableA a
WHERE a.student_id IN(?) -- result from previous query
AND a.account_status = 'AVTIVE'
AND a.semesteer = '6'
Syntactical Error
You are missing the table names in the WHERE clause. semester,account and assesor_status columns should be in some table. Add the table name like you have done for student_id column.
Logical Error
Also, I don't see the relation between TABLEA and TABLEB defined in your query. You should add that to get expected results

Categories