How to know the table name inside a fetch_array - php

I am doing a query with union from two different tables and then on the fetch_array loop I would like to know from which table out of the two I am actually grabbing, anyway without adding a flag into the table's structures. ?

The flag doesn't need to be in the table, but can easily be in the query:
SELECT 'table1' as t, ... FROM table1
UNION
SELECT 'table2' as t, ... FROM table2
...
echo $row['t'];
You don't have to select fields from a table, you can simply "select a string literal" too.

If you have columns with identical name in both tables you could use as
SELECT table1.col1 as col1, table1.col2, table1.col3 FROM table1
UNION
SELECT table2.col1 as col4, table1.col5 FROM table2
then when you do $data = fetch_assoc($q) you will have
$data["col1"] // table1.col1
$data["col2"] // table1.col2
-----------------------------
$data["col4"] //table2.col1

Related

SQL Select from table using the outcome of a previous SELECT query?

Basically, I want to Select from one table, then using the outcome select from another table and then finally echo the values I selected.
DECLARE #var1 int; /*This should become the result of Table1.Column1 */
DECLARE #var2 nchar(50); /*This should become the result of Table1.Column2 */
DECLARE #var3 nchar(50); /*This should become the final result */
SELECT #var1 = (SELECT Column1 FROM Table1 WHERE Column3 = '12345')
SELECT #var2 = (SELECT Column2 FROM Table1 WHERE Column3 = '12345')
SELECT Column1 FROM Table2 WHERE Id = #var1
Then once this has finished, PHP echo var1, var2 and var3.
I know this would be easier with 2 seperate queries but I want to keep it clean and not have to do that, does anyone know how I can do this? I know the code I provided is completely off but hopefully it makes sense what I'm trying to do.
This is what a join is for. Your first two example SELECT statements can be combined into a single statement like:
SELECT column1, column2 FROM table WHERE column3 = '12345';
You can then JOIN your table2:
SELECT
t1.column1,
t1.column2,
t2.column1
FROM Table1 T1
LEFT OUTER JOIN Table2 T2
ON t1.column2 = t2.id
WHERE t1.Column3 = '12345';
Using a LEFT OUTER JOIN here since that is the type of join that foots best with your psuedo code above. Essentially "SELECT all records that match the WHERE criteria from table1 and any records that might also match from table2 based on that ON condition. If no records match in Table2 for that ON Condition then just return NULL for that table2 column".
The result set returned will have three fields which are functionally equal to your #var1, #var2 and #var3
You can do this in two ways. Since it seems that your first query returns a single result, you can use that subselect as the expression in your second query:
SELECT #var2 = (SELECT Column2 FROM Table1 WHERE Column3 = (SELECT Column1 FROM Table1 WHERE Column3 = '12345'))
or you could use a common table expression (I'm assuming SQL Server):
with CTE_Table (var1) as
(SELECT Column1 FROM Table1 WHERE Column3 = '12345')
SELECT #var2 = (SELECT Column2 FROM Table1 WHERE Column3 = (select var1 from CTE_Table))
Something of that circumference should work. I just entered that here for context, but have not tested for syntax.

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

How to fetch row from two tables in single query?

I have three tables
1>EVENT table columns event_id, time
2>EVENT_TYPE1 table columns ref_event_id
3>EVENT_TYPE2 table columns ref_event_id
now what I want to do is to perform a query so that ref_event_id from both tables EVENT_TYPE1 and EVENT_TYPE2 can be compared to EVENT table ,in single query, and results are arranged in ascending order of time.
You can do something like this:
SELECT a.col1, a.col2
FROM EVENT a
LEFT JOIN
(SELECT col1, col2 FROM EVENT_TYPE1
UNION ALL
SELECT col1, col2 FROM EVENT_TYPE2) b ON b.col1 = a.col1 <== Comparison
This creates a single table to join with ordered as you want
SELECT combined.* FROM (
SELECT * from EVENT_TYPE1
UNION
SELECT * from EVENT_TYPE2) AS combined
I'm a little fuzzy on what you mean by 'Compared to Event table'. You can join the result of this inner select to the Event table on event_id = ref_event_id assuming ref_event_id is a foreign key into the event table.
SELECT * FROM (
SELECT * from EVENT_TYPE1
UNION
SELECT * from EVENT_TYPE2) AS combined
JOIN EVENT ON event_id = combined.ref_event_id
ORDER BY combined.time ASC

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