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.
Related
I'm new to programming and would really appreciate your help. :) So, I have a USER table and a SALES table. On the SALES table I only have name and last name of the users. On the USER table I have name, last name, USER_ID, email and etc...
I need to copy the USER_ID from the USER table to the SALES table when NAME and LAST NAME are a match.
Here is the structure:
USER_TABLE_A
USER_ID_A
NAME_LASTNAME_A
SALES_TABLE_B
ROW_ID_B
NAME_B
LASTNAME_B
USER_ID_B (empty)
So far I got both tables to show data when they intersect but have no idea where to go from here. Could anyone please help?
$sql1 = mysql_query("SELECT name_B, lastname_B, user_id_B, row_id_B FROM sales_table_B WHERE name_B IS NOT NULL AND lastname_B IS NOT NULL", $db);
$sql2 = mysql_query("SELECT name_lastname_A, user_id_A FROM user_table_A WHERE name_lastname_A IS NOT NULL", $db);
$a1 = array();
while ($row = mysql_fetch_array($sql1)) {
$id = $row['row_id_B'];
$name1.$id = $row['name_B']." ".$row['lastname_B'];
array_push($a1, $name1.$id);
}
$a2 = array();
while ($row2 = mysql_fetch_array($sql2)) {
$id2 = $row2['user_id_A'];
$name2.$id2 = $row2['name_lastname_A'];
array_push($a2, $name2.$id2);
}
$result = array_intersect($a1,$a2);
print_r($result);
Thanks in Advance!
Under the assumption that NAME_LASTNAME_A column in USER_TABLE_A is a concatenation of NAME_B and LASTNAME_B columns of SALES_TABLE_B, following UPDATE query should update the ids:
update sales_table_b
set b.user_id_b = (
select user_id_a from user_table_a
where name_lastname_a = concat(b.name_b, ' ' , b.lastname_b)
limit 1
where exists(
select user_id_a from user_table_a
where name_lastname_a = concat(b.name_b, ' ' , b.lastname_b)
)
)
Please note that in case of multiple users having same first and last name, id of the first matching user will be considered.
Thank you so much Darshan!! Your answer was missing a ) after limit 1 but with the adjustment it worked beautifully! Here is the code that worked:
UPDATE sales_table_b
SET user_id_b = (SELECT user_table_a.user_id_a
FROM user_table_a
WHERE user_table_a.name_lastname_a = CONCAT(sales_table_b.name_b, ' ' , sales_table_b.lastname_b) LIMIT 1)
WHERE EXISTS (SELECT *
FROM user_table_a
WHERE user_table_a.name_lastname_a = CONCAT(sales_table_b.name_b, ' ' , sales_table_b.lastname_b))
I need to move records to other table but I want a specific row or field like I want to move the student(table) records in the unvoted_logs but their are different field so I have to specific on inserting , I have a code but it doesn't work please I need help
$stud ="INSERT INTO unvoted_logs(idno,syearid)
SELECT idno,syearid FROM SELECT st.* FROM student st LEFT JOIN vote_logs sv ON st.idno = sv.idno AND st.syearid = sv.syearid
WHERE sv.idno IS NULL AND user_type='3'";
$qa = $db->prepare($stud);
Hi this is rough pseudocode from what I have done. By a brief explaination, I have separated the code you have provided into three steps.
Firstly SQL create a view from the inner select table.
Secondly SQL select a record from the view table
Thirdly SQL insertion by a separate query.
Hope it helps. Thanks.
$sql1 = "Create OR Replace View [student joins votes] AS
SELECT * FROM student st LEFT JOIN vote_logs sv
ON st.idno = sv.idno AND st.syearid = sv.syearid";
$qa = $db->prepare($sql1);
$qa->execute();
$sql2= "Select idno,syearid FROM [student joins votes] where WHERE idno IS NULL AND user_type='3'";
$qa = $db->query($sql2);
//only has one row in the database
if ($qa->num_rows == 1) {
// output data of each row
while($row = $qa->fetch_assoc()) {
$idno = $row["idno"];
$syearid = $row["syearid"];
break;
}
}
if($idno!=null && $syearid!=null){
$qa = $db->prepare("INSERT INTO unvoted_logs (idno, syearid)
VALUES (:idno, :syearid)");
$qa->bindParam(':idno', $idno);
$qa->bindParam(':syearid', $syearid);
$qa->execute();
}
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 two tables:
Table 1
contacts
id
email
name
lastname
postcode
straat
huisnr
woonplaats
klantnummer
bsn
land
debiteurnummer
Table 2
contacts_group
id
mail
group_name
How can I select and order this 2 tables in one query. I've tried union and left join, but did not work.
$result = mysqli_query($database->connection,
"SELECT *
FROM contacts
WHERE owner = '$session->username'
ORDER BY name ASC ,bedrijfsnaam ASC")
or die(mysqli_error());
while($roww = mysqli_fetch_array($result)){
echo $roww['email'];
echo $roww['name'];
}
Table contacts_group:
$result = mysqli_query($database->connection,
"SELECT *
FROM contacts_group
WHERE owner = '$session->username'
ORDER BY group_name ASC")
or die(mysqli_error());
while($roww = mysqli_fetch_array($result)){
echo $roww['mail'];
echo $roww['group_name'];
}
Escape your variables. You should not put the php variable unescaped in sql query. You can suffer from sql injections.
If you want to join two tables by foregin key you can do:
SELECT * FROM contacts, JOIN contacts_group ON contacts_group.id = contacts.group_id
WHERE contacts.owner = '$session->username' ORDER BY contacts.name
But you are missing group_id in contacts table or some foregin key to connect two tables.
Before do it read this topic, after try to use mysql join construction
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;