PHP SQL JOIN Avoid ID Duplicates - php

I am using this code:
SELECT * FROM Table1
JOIN Table2 USING(venue_id)
WHERE table2.location = '$MyVariable'
Then to count the number of records return:
$num_rows = mysql_num_rows($result);
echo "$num_rows";
It works great but venue_id in Table1 has lots of entries and I only want it to get one per venue_id
How can I make it so it only returns 1 venue_id instance?

Use GROUP BY clause,
SELECT * FROM Table1
JOIN Table2 USING(venue_id)
WHERE table2.location = '$MyVariable'
GROUP BY `Table1`.`venue_id`

Related

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

Transferring information from one table to another using PHP and MySQL

I have a database my_db and in it two tables t1 and t2.
t1 has two columns ID and count. ID is a list of some integers, say 1,3,4,6,7,8,9 and count is all 0s by default.
t2 also has two columns, ID2 which has a list of integers which are same as that of ID in t1. But, it is possible that they may repeat or may not be present. The second column contains some value, that isn't of much importance to this question. Clarification: ID2 can be 1,1,3,4,3,1,9,8,7,7,7.
Now, what I need to do is for every ID in t1 I need to fill in count, i.e., the number of occurrences of ID as ID2 in t2.
Running a loop through all the values in ID2 and incrementing by 1 every time in corresponding count ought to do it. But I'm unable to code it up, being new to php and sql. I can work in one table. How to work across multiple?
Maybe you can try MySQL update join?
UPDATE t1
LEFT JOIN (SELECT id2,
Count(1) AS num
FROM t2
GROUP BY id2) ref
ON t1.id = ref.id2
SET t1.count = ref.num
Please correct me if I'm wrong.
As I have understand your question is that, you need to count all ID's from Table t2 by looking ID in table t1 and then you want to insert the count of all ID's in your count column of table t1.
<?php
$query = mysql_query("SELECT * from t1");
while($record = mysql_fetch_array($query )) {
$query2 = mysql_query("SELECT COUNT(*) from t2 WHERE id='".$record['ID']."'");
$fetch = mysql_fetch_array($query2);
$count = $fetch['COUNT(*)'];
$query3 = mysql_query("UPDATE t1 SET count='".$count."' WHERE id='".$record['ID']."'");
}
?>
If you get any error. You may inform me.
Hope it will works for you.
Thanks
Another answer (with sub query)
update d1
set d1.count_d1 = (select count(d2.id)
from d2
where d2.id = d1.id group by d1.id)
SQL Fiddle
Are you looking for this :
select t1.id,count(t2.id) as total_record_in_t2
from t1
left join t2 on (t1.id=t2.id)
group by t1.id;
SQL Fiddle Example - Click to See
Here is the sql part.
First get the count of occurences of ID2 in t2:
select id2, count(*) from ts group by id2;
Then loop over the result and update t1:
update t1 set count = $value where id1 = $id2

PHP SQL Query Fields from Another Table Join

I am trying to get a query using fields from 2 tables.
I need to query Table1 but only Table2 has the variable venue_location that I need to query.
Basically I need to count all records on Table1 where Table1.venue_location = $MyVariable.
Here is what I've put together but I believe I need to use Joins for this?
Table1
- venue_id
Table2
- venue_id,
- venue_location
SELECT * FROM Table1 WHERE table1.venue_id = table2.venue_id and table2.location = '$MyVariable'
How can I do a query for this?
Use the power of join table
SELECT * FROM Table1
JOIN Table2 USING(venue_id)
WHERE table2.location = '$MyVariable'
You can get back the count of rows with mysqli_num_rows() in PHP, or change le select by SELECT COUNT(*) AS nbRow FROM ... and check of value in nbRow column
You can join two tables on venue_id and then group it by venue_id where location is your $MyVariable.
Your final query will look like:
SELECT count(table2.venue_id)
FROM Table1
JOIN Table2 ON table1.venue_id = table2.venue_id
WHERE table2.location = '$MyVariable'
GROUP BY table2.venue_id
try this
SELECT Table1.venue_id, Table2.venue_location FROM Table1 INNER JOIN Table2
ON Table1.venue_id='$MyVariable';

php mysql sort by number of rows descending

can you help me
$sql="select * from table1 where id='1,2,3,4'";
{
$sql2="select distinct column1 from table2 where column2='".$row['id']."' and left(date,10) BETWEEN '".$date_from."' AND '".$date_to."'";
}
I need to sort $sql by number of rows descending for $sql2 by id
If I understand you correctly, you want the results from $sql ordered by number of rows found by $sql2 for each row in $sql. This join should do that, it joins table2 and orders by the count, descending.
SELECT t1.id
FROM table1 t1
LEFT JOIN table2 t2
ON t1.id=t2.column2
WHERE id IN (1,2,3,4) -- should it really be = '1,2,3,4'?
AND LEFT(date,10) BETWEEN '2013-01-01' AND '2013-12-31'
GROUP BY t1.id
ORDER BY COUNT(DISTINCT t2.column1) DESC
An SQLfiddle to test with.

Pull MIN and MAX prices from database

I need to select all (*) the rows from table1, table2, table3.. but I need to select the MIN and MAX price from table 2 within this INNER JOIN. I've read up on how to do this, but how do I do this within an INNER JOIN, and how do I display it in a PHP variable.
Initial Problem: How do I display the min and max values once I pull them.. (e.g $Result['MinPrice'], $Result['MaxPrice']).
Here's my query:
$Query = mysql_query("
SELECT *
FROM table1
INNER JOIN table2 ON table1.UserID = table2.UserID
INNER JOIN tables3 ON table2.DeviceID = table3.DeviceID
WHERE table2.DeviceID = '$GetDeviceID'
");
Here is the tables structure:
table1 = usersinfo
UserID UserFirstName UserLastName UserDisplayName
1 John Doe John D.
table2 = listings
ListingID UserID DeviceID
11 1 2
table3 = devices
DeviceID
2
If you really want to do what you're asking in this way you can use the query that is displayed below. This does, however, return a lot of duplicate rows if you have multiple rows returned when querying. Try it and see if it works.
$Query = mysql_query("
SELECT table1.*, table2.*, table3.*,
MIN(table2.price) as minny,
MAX(table2.price) as maxxy
FROM table1
INNER JOIN table2 ON table1.UserID = table2.UserID
INNER JOIN tables3 ON table1.DeviceID = table3.DeviceID
WHERE table1.DeviceID = '$Something'
GROUP BY table2.ListingAskingPrice
");
Then get this value by doing $result['minny'] and $result['maxxy']

Categories