I have tables like this
COUNT tbl
id, userid, linkid, count
4
1
6
LINKS tbl
id, linkname, linkurl
What i want to do is to order the 'linkname' column in order of the count column and put it in an array. I am struggling becasue i am not understanding how to use JOIN.
I need to get linkid WHERE userid = $userid
Try this:
$userid = intval( $userid ); // Hopefully it's already an integer,
// but protect yourself from SQL Injection
SELECT linkname, C.count FROM Links INNER JOIN `Count` C ON C.linkid = Links.id
WHERE userid = $userid
ORDER BY C.count ASC
Try this: SELECT * FROM Links L JOIN Count C ON L.id = C.linkid then you should have a count column.
Also, I recommend you don't use "count" as the name of a table since it is a SQL reserved word.
Related
I'm having difficulty understanding how to Order a query by data from another table.
The existing query is: SELECT ID FROM UserTour WHERE Live = 1 ORDER BY LastUpdated DESC
This obviously Orders by the column 'LastUpdated' in the table 'UserTour'
However, I need it to be ordered by the column 'LastUpdated' which is in another table 'ImageLinks', Where 'TypeID' = 16 (again in 'ImageLinks').
I hope that makes sense.
So it would be something like: $ids = #mysql_values('SELECT ID FROM UserTour WHERE Live = 1 ORDER BY ('Select ID FROM 'ImageLinks' Where TypeID = 16 Order by LastUpdated DESC')');
Any help would be appreciated on how to do this. Cheers
If there is no relationship between the two tables your query in your question will look like this
select id from
(
SELECT
ID
, (Select ID FROM ImageLinks Where TypeID = 16
Order by LastUpdated DESC limit 1) as order_val
FROM UserTour
WHERE Live = 1
) x
ORDER BY x.order_val
which will work but will not do not any ordering as the order_val column will have a fixed value.
If the IDs are linked 1:1 (no indication that they are, but just supposin') we could do this:
select u.id
from UserTour u inner join ImageLinks i on u.ID = i.ID
where u.Live = 1 and i.TypeID = 16
order by i.LastUpdated desc
If the above is incorrect then you will have to decide how the two tables are related and join them correspondingly.
In other words, If the tables are in no way connected, then you cannot provide an ordering of one table's data based on a column in the other.
UPDATE
select
i.LinkID
, i.LastUpdated
from UserTour u inner join ImageLinks i
on u.ID = i.LinkID
where u.Live = 1 and i.TypeID = 16
group by i.LinkID, i.LastUpdated
order by i.LastUpdated desc LIMIT 30
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
I am trying to join my users table with another table using the following query...
SELECT * FROM (`activities`)
JOIN `users` ON `users`.`id` = `activities`.`user`
WHERE `user_subdomain` = 'hi' OR user_subdomain = ''
ORDER BY `activities`.`id` desc
LIMIT 10
Is there any way to do the join so that the id of the user does not replace the id of the activity?
For example, currently if there is an activity with the id of 10 and the user 2 the id will be replaced by the id of the users table and show as 2 after I run the query.
Thanks a lot for the help!
Whenever you are joining tables, you ought to be explicit about the columns you select rather than using SELECT *, and specify column aliases for them when the same column name is used in multiple tables.
SELECT
activities.id,
activities.othercol,
/* Alias to userid */
users.id AS userid,
users.name,
users.anothercolumn
FROM (`activities`)
JOIN `users` ON `users`.`id` = `activities`.`user`
WHERE `user_subdomain` = 'hi' OR user_subdomain = ''
ORDER BY `activities`.`id` desc
LIMIT 10
Though it isn't strictly necessary to prepend the table name to each, unless the column names are the same.
SELECT
activities.id AS activityid,
othercol,
users.id AS userid,
name,
anothercolumn
Here is my code but im sure its not the correct way of doing this.
mysql_query("SELECT * FROM BlockUsers
WHERE OwnerID =
(SELECT ID FROM UserAccounts WHERE Code='$UserCode')
AND
BlockID =
(SELECT ID FROM UserAccounts WHERE Code='$BlockUserCode')
LIMIT 1", $DB)
Can someone help? thanks!
Yes, but when you're doing an equality test like that (=, <, >, etc...), the subquery has to return a single value. Otherwise it'd be somevalue = [list of result rows], which makes no sense.
You'd want:
SELECT * FROM BlockUsers
WHERE OwnerID IN (SELECT ID FROM UserAccounts WHERE.....)
^^--- use 'in' instead of '=';
SELECT * FROM BlockUsers
WHERE OwnerID IN
(SELECT ID FROM UserAccounts WHERE Code='$UserCode')
AND
BlockID IN
(SELECT ID FROM UserAccounts WHERE Code='$BlockUserCode')
LIMIT 1
or
SELECT * FROM BlockUsers AS bu
INNER JOIN UserAccounts AS ua1 ON ua1.ID = bu.OwnerID
INNER JOIN UserAccounts AS ua2 ON ua2.ID = bu.BlockID
WHERE ua1.Code = '$UserCode' AND ua2.Code = '$BlockUserCode'
LIMIT 1
I think. I didn't test any of this, but I'm pretty sure it's close.
Edit:
I just noticed you're using MySQL. You definitely want to do inner joins instead of sub selects. In MySQL those sub selects will create derived tables which have no indexes. Looking for OwnerID and BlockID in those derived tables will do a full table scan of them. This may not matter if $UserCode and $BlockUserCode will narrow the results of the sub selects down to a single row, but if they return quite a few rows it will really slow your query down.
Instead of using subqueries, you can just JOIN UserAccounts to get the rows you want.
SELECT BlockUsers.* FROM BlockUsers
JOIN UserAccounts as UA1 ON Code='$UserCode' AND OwnerID = UA1.ID
JOIN UserAccounts as UA2 ON Code='$BlockUserCode' AND BlockID = UA2.ID
LIMIT 1
Yes you can, Subqueries and you can find the official mysql reference here: http://dev.mysql.com/doc/refman/5.0/en/subqueries.html
and from your query i think you are good to go assuming your subqueries only return 1 value, or as #Marc B points use IN instead of the equal sign.
Try to use
SELECT * FROM BlockUsers, UserAccounts
WHERE (OwnerID = ID and BlockID=ID and Code in ('$BlockUserCode', '$UserCode')
LIMIT 1
Im trying to construct a query that goes over 3 tables and im COMPLETELY stumped ... my knowledge limit is basic 1 table query and i need some help before i stick my head in a blender.
I have the following query
SELECT * FROM internalrole WHERE introle = $imarole
Im fine with that part .. its the next thats getting me all stressed.
That query returns the following columns ( id, user_id, introle, proven, used )
What i then need to do is take the user_id from the results returned and use it to get the following
SELECT * FROM users WHERE id = user_id(from previous query) AND archive = 0 and status = 8
I need to put that into 1 query, but wait, theres more .... from the results there, i need to check if that user's 'id' is in the availability table, if it is, check the date ( column name is date ) and if it matches todays date, dont return that one user.
I need to put all that in one query :S ... i have NO IDEA how to do it, thinking about it makes my head shake ... If someone could help me out, i would be eternaly grateful.
Cheers,
Use INNER JOIN, which links tables to each other based on a common attribute (typically a primary - foreign key relationship)
say an attribute, 'id', links table1 and table2
SELECT t1.att1, t2.att2
FROM table1 t1
INNER JOIN table2 t2
ON t1.id = t2.id --essentially, this links ids that are equal with each other together to make one large table row
To add more tables, just add more join clauses.
SELECT u.*
FROM internalrole ir
INNER JOIN users u
ON ir.user_id = u.id
AND u.archive = 0
AND u.status = 8
LEFT JOIN availability a
ON ir.user_id = a.user_id
AND a.date = CURDATE()
WHERE ir.introle = $imarole
AND a.user_id IS NULL /* User does NOT exist in availability table w/ today's date */
EDIT: This second query is based on the comments below, asking to show only users who do exist in the availability table.
SELECT u.*
FROM internalrole ir
INNER JOIN users u
ON ir.user_id = u.id
AND u.archive = 0
AND u.status = 8
INNER JOIN availability a
ON ir.user_id = a.user_id
WHERE ir.introle = $imarole
Hmm, maybe something like this
SELECT * FROM users WHERE id IN (SELECT user_id FROM internalrole WHERE introle = $imarole) AND archive = 0 and status = 8;
A handy thing for me to remember is that tables are essentially arrays in SQL.
HTH!
Nested queries are your friend.
SELECT * FROM users WHERE id in (SELECT user_id FROM internalrole WHERE introle = $imarole) AND archive = 0 and status = 8
Alternatively joins:
SELECT * FROM users INNER JOIN internalrole ON users.id = internalrole.user_id WHERE internalrole.user_id = $imarole AND users.archive = 0 and users.status = 8