This question already has answers here:
SQL query return data from multiple tables
(6 answers)
Closed 6 years ago.
I have two tables in a DB (table_1 and table_2), Each of them has a mutual column called Name.
I am currently using the following code to import some data (Name,status) only from table_1:
/* database section start */
$mysqli = new mysqli("z","z","z","z");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* database section end */
// Choose Relevant items, and turn them into an array
$item_array = array(
'item1',
'item2',
'item3'
);
//implode items, turn into string
$item_implode = join("','", $item_array);
//declare an overall array for result
$product = array();
$result = $mysqli->query("SELECT Name, Status as status from table_1 where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode');");
while($row = $result->fetch_assoc()) {
$product_name = $row['Name'];
// find all keys in $item_array which value is the products
$keys = array_keys($item_array, $product_name);
foreach ($keys as $key) {
// add values for these keys
$product[$key + 1]["Name"] = $row['Name'];
$product[$key + 1]["status"] = $row['status'];//
}
}
What should I add to this code if I want to import data from table_2 as well (e.g., columns named color, date_added)?
My objective is to have these keys:
$product[$x]["Name"]
$product[$x]["status"]
$product[$x]["color"]
$product[$x]["date_added"]
EDIT:
That long thread doesn't answer my question. The code isn't similar to the code I'm using, and I want to know how to apply the UNION exactly in this concrete case.
I've tried using:
$result = $mysqli->query
("(SELECT Name, status as status from table_1 )
UNION
(SELECT Name, color as color from table_2 )
where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode');");
while($row = $result->fetch_assoc()) {
But I get fatal error on the last line.
EDIT2:
Still getting an error:
$result = $mysqli->query
("(SELECT Name, status as statu table_1 where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode') )
UNION (SELECT color from table_2 where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode') );");
while($row = $result->fetch_assoc()) {
$result = $mysqli->query("SELECT table_1.Name, table_1.Status,table_2.color,table_2.date_added from table_1 inner join table_2 on table_1.Name=table_2.Name where table_1.Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode');");
(SELECT Name, Status as status FROM table_1 t1)
UNION
(SELECT color, date_added FROM table_2 t2)
Change your query, and try to use: INNER JOIN table_2
I can`t make the query for you, because I don't have your data...
Build your Query with a join.
$query="SELECT t1.Name, t1.Status as status, t2.color, t2.date_added) from "
."table_1 t1 "
."LEFT JOIN table_2 t2 ON t2.Name "
."where t1.Name IN ('$item_implode') "
."AND t2.Name = t1.Name "
."ORDER BY FIELD (t1.Name, '$item_implode');";
Related
i have three table with same value of columns. example: say i have three table "table1", "table2", "table3" and each columns has "id", "title", "description", "category", "date", "thumbnail", "admin". now i'm trying to get all data from those three table. but there is a think, i want to check with if statement. if table1 not match with id, check table2. if table2 not match with id, check table3 and at last show the data. please check my below code, i'm trying to get data from those three table:
<?php
include('config/database.php');
$id=$_GET['single'];
$query=mysqli_query($conn,"select * from table1, table2, table3 where id='$id' ");
while($row=mysqli_fetch_array($query)){
$title=$row['title'];
$date=$row['date'];
$admin=$row['admin'];
$thumbnail=$row['thumbnail'];
$description=$row['description'];
$category=$row['category'];
}
?>
please help me to get all data from those three table with if statement
it will be better to understand if you post an answer. thank you in advance.
Use a UNION of 3 queries.
$sql = "
SELECT * FROM (
SELECT 1 AS tnum, * FROM table1 WHERE id = ?
UNION ALL
SELECT 2 AS tnum, * FROM table2 WHERE id = ?
UNION ALL
SELECT 3 AS tnum, * FROM table3 WHERE id = ?
) AS x
ORDER BY tnum
LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param('iii', $id, $id, $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ($row) {
$title = $row['title']
$date=$row['date'];
$admin=$row['admin'];
$thumbnail=$row['thumbnail'];
$description=$row['description'];
$category=$row['category'];
}
Adding the tnum column to the result orders them so the table1 data is preferred, then table2, finally table3.
i have two tables with two columns:
Table1 table1
Columns id, address1
Table2 table2
Columns id, address2
I just wont to compare the addresses in the column address1 with column address2 to find out duplicate addresses. The table2.address2 contains some addresses from table1.address1
If there is a match then, make an update for example on the table2 column match put 1 else put nothing...
Column match is just an example!!!
here is what i have:
// table 1
$query = "SELECT id, address1 FROM table1";
$sqldata = mysql_query($query);
while ($row = mysql_fetch_array($sqldata, MYSQL_BOTH) ) {
$kr_id = $row['id'];
$address1 = $row['address1'];
}
// table 2
$query = "SELECT id, address2 FROM table2";
$sqldata2 = mysql_query($query);
while ($row2 = mysql_fetch_array($sqldata2, MYSQL_BOTH) ) {
$id = $row2['id'];
$address2 = $row2['address2'];
if ($row2[$address2] == $address1) {
// make an SQL - Update
}
}
thans for any help!!!
You can use update with join:
UPDATE Table2 t2
INNER JOIN Table1 t1
ON(t1.mk_adress = t2.adress)
SET t2.match = 1
You may have to adjust the column names a little bit, couldn't figure out which table you want to be updated.
I need to display in alphabetical order a list of name and surname (order by surname).
The problem is I can't do a ORDER BY in SQL query because I retrieve my users ID in one table and retrieve the informations in another table.
My PHP code:
$sql = "select id FROM $table_name";
$result = $wpdb->get_results($sql);
foreach ($result as $record) {
$id = $record->id;
$sql2 = "select field_name, field_val FROM $table_name2 where sub_id = $id";
$result2 = $wpdb->get_results($sql2);
foreach ($result2 as $record2) {
if($record2->field_name == "Nom :") {
$surname = ucfirst(stripslashes($record2->field_val));
}
if($record2->field_name == "Prénom :") {
$name = ucfirst(stripslashes($record2->field_val));
}
}
echo $name . " " . $surname . "<br/>";
}
Here the architecture of the second table:
f_id sub_id field_name field_val
127 19 Prénom : Philippe
128 19 Nom : Nailloux
129 20 Prénom : John
130 20 Nom : Drumond
Have you an idea how I can display my list ordered by surname alphabetically?
Thanks.
You can do the trick by using this SQL query :
SELECT t1.id AS user_id,
t2.field_val AS surname,
t3.field_val AS name
FROM $table_name t1
JOIN $table_name2 AS t2
ON ( t2.sub_id = t1.id
AND t2.field_name = 'Nom :' )
JOIN $table_name2 AS t3
ON ( t3.sub_id = t1.id
AND t3.field_name = 'Prénom :' )
ORDER BY t2.field_val
The query will return all the infos needed (user_id, surname and name) ordered by surname.
Use subqueries!
In your example, let's say you have 100 users.
In first query you get your users ids, then for each user you query database for one's data. That's 101 queries for a simple operation! What if you have 10 visits per seconds? That's more than 1000 queries.
There are many strategies (subquery, join, two queries with in () in second one) but in this case consider that:
SELECT
field_name, field_val
FROM
$table_name2
WHERE
sub_id IN(
SELECT
id
FROM
$table_name
) as sq1
ORDER BY field_val ASC;
Also consider using PHP PDO, or at least proper escaping of data you put in queries.
I have a script designed to print out values of students who have accrued more than 3 tardies. I want this script to print out both the student name, and the amount of times they've been tardy, but so far I've been only able to print out their names with the following script:
$sql = "select DISTINCT StudentID,classid,date from attendance_main where status = 'Tardy' AND classid like '%ADV%'";
$result = mysql_query($sql) or die (mysql_error());
while($row=mysql_fetch_array($result)) {
$studentid = $row['StudentID'];
$sql2 = "select distinct StudentID,classid,date from attendance_main where StudentID = '$studentid' AND status = 'Tardy' AND classid like '%ADV%'";
$result2 = mysql_query($sql2) or die (mysql_error());
while($row2=mysql_fetch_array($result2)) {
$tardycount = mysql_num_rows($result2);
$studentid = $row2['StudentID'];
if($tardycount >= 3) {
$sql3 = "select * from students where rfid = '$studentid'";
$result3 = mysql_query($sql3) or die (mysql_error());
while($row3=mysql_fetch_array($result3)) {
$fname[] = $row3['fname'];
}
}
}
}
$newdata = array_unique($fname);
foreach ($newdata as $value) {
echo $value;
}
I can't think of how to intuitively do this. Keeping it all in the while loop didn't work (I had multiple results coming up for the same students despite requesting unique entries) so using array_unique was the only method I could think of.
Thanks for any help!
Something like this:
SELECT
attendance_main.StudentID,
students.fname,
COUNT(attendance_main.*) AS `times_tardy`
FROM
attendance_main
INNER JOIN
students
ON
attendance_main.StudentID = students.rfid
WHERE
attendance_main.status = 'Tardy'
AND
attendance_main.classid like '%ADV%'
GROUP BY
attendance_main.StudentID
HAVING
`times_tardy` > 3
Joining the two tables gets you the tardy count and student's name in one query, and the GROUP BY and HAVING clause that get you only the students with more than 3 tardy entries.
You can (and should) do almost everything in SQL. It should look something like this.
select StudentID, classid, date count(*)
from attendance_main
where status = 'Tardy' AND classid like '%ADV%'"
left join student on student.rfid = attendance_main.StudentId
group by StudentId
having count(*) > 3;
Here's how it works.
select the results you want to work with:
select StudentID, classid, date count(*)
from attendance_main
where status = 'Tardy' AND classid like '%ADV%'"
Join the students to your result set on the common id
left join student on student.rfid = attendance_main.StudentId
group everything by student. We use count(*) to get the number of items. We know we're only dealing with tardies because of the where clause in the select.
group by StudentId
limit the results to only tardies above 3 with the having claues (this is like a where clause for the group by)
having count(*) > 3;
I have the following query:
SELECT *
FROM scool
LEFT JOIN people as t1 ON t1.scool_fk=scool.id AND t1.lang_gk='en'
LEFT JOIN people as t2 ON t2.scool_fk=scool.id AND t2.lang_gk='fr'
...
(this is nonsense query, only for example)
With SELECT * it query returns french values
With SELECT t1.* it query returns english values
The only possible solution i know is
SELECT t1.name as name_en, t2.name as name_fr
This don't like me because i can't automatize the selects in my program
Is possible to be return all values from SELECT with tablename.columnname or other similar solution, for get values in php?
Use mysql_fetch_field and properties table and name:
<?php
mysql_connect("", "", "");
mysql_select_db("test");
$res = mysql_query("SELECT * FROM t_ai a1 CROSS JOIN t_ai a2 LIMIT 1") or die(mysql_error());
$names = array();
for ($i = 0; $i < mysql_num_fields($res); $i++) {
$meta = mysql_fetch_field($res, $i);
array_push($names, "$meta->table.$meta->name");
}
print implode($names, "\t") . "\n";
?>
$ php phptest.php
a1.id a2.id