join tables issue for member list - php

I have 2 tables I am struggling to join information I think I am overlooking something.
users
-----
uid username rank_id reg_date country
mil_rank
-----
rank_id rank_title
Desired output:
---------------
Username Rank Title Reg Date Country
john sgt today usa
$sql = "SELECT * users.uid, mil_rank.rank_title ".
"FROM users, mil_rank ".
"WHERE users.rank_id = users.rank_title";
I would like to select all from both tables if possible

There are apostrophe " and points . too. Here's the good syntax
$sql = "SELECT users.uid, mil_rank.rank_title
FROM users, mil_rank
WHERE users.rank_id = users.rank_title";

You need to use the rank_id key to tie the two tables together:
SELECT users.username, mil_rank.rank_title, users.reg_date, users.country
FROM users, mil_rank
WHERE users.rank_id = mil_rank.rank_id
Since the rank_id column is present in both tables and you don't want that or the uid column in your output you probably also don't want to just select *.

Try with this example
SELECT u.uid, u.username, u.rank_id, u.reg_date, u.country, m.rank_id, m.rank_title
FROM users u, mil_rank m
WHERE u.rank_id = m.rank_id

If you wish to use a JOIN then this is how you would write that query
SELECT u.username, u.reg_date, u.country, m.rank_title
FROM users u
JOIN mil_rank m ON m.rank_id = u.rank_id
If you want this for a specific rank then
SELECT u.username, u.reg_date, u.country, m.rank_title
FROM users u
JOIN mil_rank m ON m.rank_id = u.rank_id
WHERE m.rank_title = 'sgt'
In answer to your comment, Yes
SELECT u.username, u.reg_date, u.country, m.rank_title
FROM users u
JOIN mil_rank m ON m.rank_id = u.rank_id
WHERE u.status_id != 1
Maybe if you read through a Basic SQL Tutorial you would be able to do the basic stuff yourself.

Related

PHP/MYSQL counting orders

Here is database table:
$sql[2] = "SELECT u.* , oi.* , COUNT(oi.user_id) AS count
FROM users u, order_items oi
WHERE u.id=oi.user_id ";
$result3= mysqli_query($conn,$sql[2]) or die(mysqli_error());
if (mysqli_num_rows($result3) > 0) {
while ($record = mysqli_fetch_array($result3)) {
echo $record['count'];
}
}
I want to count how much order have every user. Example: Like Thomas have 3 order, but my code is writing 4, i want to write Thomas (3), Gracian(1). Any idea how to fix it ?
Use this query:
SELECT u.id,
COUNT(oi.user_id) AS orderCount
FROM users u
LEFT JOIN order_items oi
ON u.id = oi.user_id
GROUP BY u.id
The reason we count user_id from the order_items table is because of the edge case where a given user has no orders. In this case, we want to make sure that his count would appear as zero. The COUNT function ignores NULLs, which is what we want.
There is another way to perform the sql query using subqueries:
SELECT id,
email,
address,
name,
(SELECT count(user_id) FROM order_items WHERE user_id = users.id) AS orderCount FROM users;

Difficulty with join 3 tables in a query in php

My database has 3 tables i wish to access in the select query but I cannot seem to get it to work. Selecting from 2 tables works fine so I know everything else is working apart from my code for selecting from 3 tables. My database has been created on PHPmyadmin
The Tables are as follows:
forum_replies
reply_id
topic_id
user_id
reply_text
reply date
forum_topics
topic_id
category_id
user_id
topic_title
topic_description
topic_date
users
user_id
username
This is the code I have tried to use and shows the fields I wish to select:
$queryreply = "SELECT forum_replies.reply_id, forum_replies.topic_id, forum_replies.user_id,
forum_replies.reply_text, forum_replies.reply_date, users.user_id, users.username
forum_topics.topic_id,forum_topics.topic_title, forum_topics.topic_date
FROM forum_replies
JOIN forum_topics
ON forum_replies.topic_id = forum_topics.topic_id
JOIN users
ON forum_replies.user_id = users.user_id
";
$result = mysql_query($queryreply) or die (mysql_error());
$row = mysql_fetch_array($result);
Example in code would be appreciated. Thanks
Use this query:
SELECT a.reply_text, a.reply_date, b.topic_title, c.username
FROM forum_replies a
LEFT JOIN forum_topics b ON a.topic_id=b.topic_id
LEFT JOIN users c ON a.user_id=c.user_id
// apply WHERE, ORDER, GROUP if needed
Apart from syntax errors, you should use LEFT JOIN and table alias in your case.
To show also the topic creator's username, you can adjust the query to the following:
SELECT a.reply_text, a.reply_date, b.topic_title, c.username AS reply_user, (SELECT username FROM users WHERE user_id=b.user_id) AS topic_creator
FROM forum_replies a
LEFT JOIN forum_topics b ON a.topic_id=b.topic_id
LEFT JOIN users c ON a.user_id=c.user_id
// apply WHERE, ORDER, GROUP if needed
You miss the , after users.username..
SELECT forum_replies.reply_id, forum_replies.topic_id, forum_replies.user_id,
forum_replies.reply_text, forum_replies.reply_date, users.user_id, users.username,
forum_topics.topic_id,forum_topics.topic_title, forum_topics.topic_date

mysql joining two table

table user:
id_u* f_name l_name
----------------------
1 andi mitchel
2 sarah bench
3 kirsty larx
table voucher:
id_v* id_user id_target
1 1 2
2 2 3
quite confused how to join those table with two foreign keys
$db->query("SELECT * FROM voucher v
LEFT JOIN user u ON u.id_u = v.id_user
LEFT JOIN user u1 ON u1.id_u = v.id_target
WHERE .... ")
echoing while loop... and returns nothing??
while($r = $q->fetch_array(MYSQLI_ASSOC)) :
echo $r['u.f_name'];
echo $r['u1.f_name'];
endwhile;
Your JOIN seems absolutely correct. The only issue is that you have joined table user twice, therefore you have columns with same name (like f_name). The database will assign different (but arbitrary) names to these columns. You can override this behaviour with the AS keyword:
$db->query("SELECT v.*
, u.f_name AS user_f_name
, u.l_name AS user_l_name
, ta.f_name AS target_f_name
, ta.l_name AS target_l_name
FROM voucher v
LEFT JOIN user u ON u.id_u = v.id_user
LEFT JOIN user ta ON ta.id_u = v.id_target
WHERE .... ")
Then:
while($r = $q->fetch_array(MYSQLI_ASSOC)) :
echo $r['user_f_name'];
echo $r['target_f_name'];
endwhile;
And I think you can replace the LEFT JOINs with (inner) JOINs. Unless you have id_user or id_target values referencing non-existing userids (id_u).
It looks like you are asking for all people who are in the voucher table regardless of them being in position 1 (user) or position 2 (target)... Then, showing that person's name.
This query does a pre-query of each possible person and their position basis (via WhichPosition).
SELECT STRAIGHT_JOIN
AllVoucherUsers.WhatPosition,
u.*
FROM
( select distinct
v.id_user,
'1' as WhatPosition
from voucher v
union select distinct
v.id_target as id_user,
'2' as WhatPosition
from voucher v
) AllVoucherUsers
join users u
on AllVoucherUsres.id_user = u.id_u
If you only want ONE instance of a given person -- REGARDLESS of their position, just strip out all instances of the "WhatPosition" reference...
SELECT STRAIGHT_JOIN
u.*
FROM
( select distinct
v.id_user
from voucher v
union select distinct
v.id_target as id_user
from voucher v
) AllVoucherUsers
join users u
on AllVoucherUsres.id_user = u.id_u
SELECT * FROM voucher v
LEFT JOIN user u ON u.id_u = v.id_user OR u.id_u = v.id_target
WHERE ....
how about:
SELECT * FROM voucher JOIN user ON id_user = id_u
Simpler still:
SELECT * FROM voucher, user WHERE id_user = id_u

PHP: WHERE in another table

Yes so im building an query from the advanced search form.
I have this:
$query = "SELECT * FROM users WHERE 1 ";
$query .= "AND sex = '$sex' ";
for now, next im going to have AND birthday.. but then i dont know how to do it, because users birthday is stored in users_profile
So please correct me, how can i:
$query .= "AND birthday in users_profile = '1'";
Is this possible even, or should i reconstruct it and put birthday in users instead..
update:
in users, the id column there, is binded with users_profileĀ“s uID.
So in users_profileĀ“s uID column, there is the users id.
I assume your users_profile table is linked to the users table?
SELECT u.*, up.birthday
FROM users u
INNER JOIN users_profile up
ON u.user_id = up.user_id
WHERE sex = '$sex'
Here an Inner Join is used. The reason we can use u instead of users and up instead of users_profile is because we have set up the aliases "users u" and "users_profile up"
You need to look at the syntax for JOIN.
You need a way to join individual related rows in the two tables, something like:
SELECT u.* FROM users u, users_profile p
WHERE u.sex = 'M'
AND p.birthday = '1'
AND u.userid = p.userid;
I don't understand why you have separate tables for user and for users_profile, but you need to JOIN the two tables:
SELECT U.*
FROM users U
LEFT JOIN users_profile P
ON P.uID = U.uID
AND P.birthday = '1'
WHERE U.sex = '$sex'
Very possible, given you have the foreign key to the users_profile table.
Let's say the primary key in the users table is named 'id', and the users_profile table contain a field called 'uid' which point to the users table, you'd normally create the query like this:
SELECT * FROM users u, users_profile p WHERE u.id = p.uid
AND u.sex = '$sex' AND u.birthday = 1

Friendship System Sql Structure & Query

I am coding a friendship system and it has two tables.
members
id
username
password
friends
id
user_id
friend_id
status
Let's say that i want a query that can select the friends IDs of the member $userId how possible to make this in one query?
I found a solution which is to make 2 queries. The fist selects the friends WHERE user_id = $userId AND the second selects friends WHERE friend_id = $userId and then MIX them in one array. If there is no other solution I'm going to use it.
please any ideas for both the SQL structure & Queries?
Use:
SELECT f.friend_id
FROM FRIENDS f
WHERE f.user_id = $user_id
UNION
SELECT t.user_id
FROM FRIENDS t
WHERE t.friend_id = $user_id
Using UNION will remove duplicates. UNION ALL would be faster, but it doesn't remove duplicates.
If you want to get the information for the friends from the MEMBERS table, use:
SELECT m.*
FROM MEMBERS m
JOIN (SELECT f.friend_id 'user_id'
FROM FRIENDS f
WHERE f.user_id = $user_id
UNION
SELECT t.user_id
FROM FRIENDS t
WHERE t.friend_id = $user_id) x ON x.user_id = m.id
BTW: I hope you're using mysql_escape_string on the variables, otherwise you risk SQL injection attacks:
You should be able to try using
SELECT m.*
FROM friends f INNER JOIN
members m ON f.friend_id = m.user_id
WHERE f.user_id = $userId
This will give you all the Friends details
To get BOTH have a look at
SELECT DISTINCT CASE WHEN f.user_id = $userId then f.friend_id else f.user_id END CASE
FROM friends f
WHERE f.user_id = $userId
OR f.friend_id = $userId
Why not inserting 2 rows for 1 friendship. For example:
Let's say we have 2 user will become friends
User_id : 1 &
Friend_id : 2
insert into friends (user_id, friend_id, status) values (1,2,0)
insert into friends (user_id, friend_id, status) values (2,1,0)
so you can select easily by simple select query.
Also it will ease the pain for your likely next question "How to find Mutual Friends".
Since you're asking for something simple like:
SELECT friend_id FROM friends WHERE user_id = id; [fill in the id]
I'll give you something fancier:
SELECT * FROM members AS m
WHERE m.id
IN (SELECT f.friend_id FROM friends AS f
WHERE f.user_id = (SELECT pm.id FROM members AS pm
WHERE pm.username = 'amindzx'));
Granted using a join over a sub-query would be better.
Also, there's no need for an id in the friends column, because only one relationship between a user_id and a friend_id should exist; these can both be described as the id columns in unison.

Categories