Select From Inner join - PHP/MYSQL - php

I am struggling with a MYSQL query - I have 2 tables :
Table 1 (info) containing UID, first_name, last_name.
Table 2 (card) containing UID, pic .
What I am trying to do is get all results into an array:
WHERE UID IN '$ids' AND LEFT(last_name,1) = '$letter' ORDER BY last_name, first_name ASC
I figured an INNER JOIN so my current code is:
("SELECT UID, first_name, last_name, pic FROM
(SELECT info.first_name,info.last_name,card.pic FROM info
INNER JOIN card ON info.UID=card.UID)
WHERE LEFT(last_name,1) = '$letter' ORDER BY last_name, first_name ASC")
This is producing the following error though:
'Every derived table must have it's own alias'.
Am I going about this the right way with inner join, and how do I give the derived table an alias? Thanks in advance!

select b.UID, g.first_name, g.last_name, b.pic
from user_data.general_info g
inner join user_data.Bcards b on g.UID = b.UID
where LEFT(g.last_name, 1) = '$letter'
order by g.last_name, g.first_name asc

The inner query should be named.
SELECT users.UID, users.first_name, users.last_name, users.pic FROM
(SELECT info.first_name,info.last_name,card.pic FROM user_data.general_info
INNER JOIN user_data.Bcards ON general_info.UID=Bcards.UID) users
WHERE LEFT(users.last_name,1) = '$letter' ORDER BY users.last_name, users.first_name ASC

Related

Is it possible to have a DISTICT statement only on one varible?

I only want the SELECT DISTINCT statement on 'yearLevel' (as I don't want any duplicates only on yearLevel)
image of data displayed on screen
For example I only want one 'yearLevel' 12 record in the table, and for that to be the one with the lowest 'totalSeconds'
code
$sql = "SELECT firstName, lastName, yearLevel, totalSeconds
FROM studentInformation
JOIN record
ON studentInformation.studentId = record.student_Id
ORDER BY totalSeconds ASC
LIMIT 1 ";
Is it possible to do this -
$sql = "SELECT firstName, lastName, DISTINCT yearLevel, totalSeconds
FROM studentInformation
JOIN record
ON studentInformation.studentId = record.student_Id
ORDER BY totalSeconds ASC
LIMIT 1 ";
Provided that "firstName" and "lastName" are in table "studentInformation", and "yearLevel" as well as "totalSeconds" are in table "record" this query should be working. It uses a correlated subquery. I did not test this; if it doesn't work please let me know.
SELECT a.firstName, a.lastName, b.yearLevel, b.totalSeconds
FROM studentInformation a
INNER JOIN record b ON a.studentId = b.studentId
WHERE b.totalSeconds = ( SELECT min(totalSeconds)
FROM record
WHERE yearLevel = b.yearLevel )
ORDER BY b.totalSeconds ASC
Assuming that only "totalSeconds" is in table "record" this could work, too.
SELECT a.firstName, a.lastName, a.yearLevel, b.totalSeconds
FROM studentInformation a
INNER JOIN record b ON a.studentId = b.studentId
WHERE b.totalSeconds = ( SELECT MIN(d.totalSeconds)
FROM studentInformation c
INNER JOIN record d ON c.studentId = d.studentId
WHERE c.yearLevel = a.yearLevel )
ORDER BY b.totalSeconds ASC

Fetching data from two tables using a specific criteria

What I am doing is: Fetching data to show the products to user, so that he/she can rate products. Which is working fine using below query.
$query = " SELECT table_products.product_name,
table_products.product_expiry,
table_users.name,
table_users.email
FROM table_products
INNER JOIN table_users ON table_users.user_id = table_products.user_id
ORDER BY table_users.id DESC";
Now what I want to ask is: How to show only those products that the user hasn't rated yet. Once a user rates a product, that product should not be fetched by the query for that user again.
I've 3 tables
table_users (user_id, name, email)
table_products (product id_, user_id, product_name, product_expiry)
table_rating (rating_id, user_id, product_id, rating)
and I want to fetch data from 2 tables
table_users, table_products
data to be fetched
table_users.name,
table_users.email,
table_products.product_name,
table_products.product_expiry
How to set query for this task for a specific user_id?
Thanks for your time and help :)
There are multiple ways, You need join table, group by and use having clause, please refer to the image.
Use this query
SELECT table_products.product_name,
table_products.product_expiry,
table_users.name,
table_users.email
FROM table_products
INNER JOIN table_users ON table_users.user_id = table_products.user_id
LEFT JOIN table_rating on table_products.product_id=table_rating.product_id
WHERE table_rating.product_id IS NULL
ORDER BY table_users.id DESC
You can join the ratings table and count the number of ratings then check it in the where clause, something like this (untested):
$query = "SELECT
table_products.product_name,
table_products.product_expiry,
table_users.name,
table_users.email,
count(table_rating.id) as ratings
FROM table_products
INNER JOIN table_users ON table_users.user_id = table_products.user_id
left join table_rating ON table_rating.product_id = table_products.id
where ratings = 0
ORDER BY table_users.id DESC";
SELECT
table_products.product_name,
table_products.product_expiry,
table_users.name,
table_users.email
FROM table_products
INNER JOIN table_users ON table_users.user_id = table_products.user_id
LEFT JOIN table_rating ON table_products.user_id = table_rating.user_id
AND table_products.product_id = table_rating.product_id
WHERE table_rating.product_id IS NULL
ORDER BY table_users.user_id DESC

Multiple Counts in MYSQL PHP Query

I'm trying to create a leaderboard but i'm not sure how to do the mysql query.
I would like to count all the levels from a player in the skills table and get the total Level and count all the experience from a player in the experience table and get the Total Exp along with displaying the persons name from the users column.
There is 3 tables factions_mcmmo_users, factions_mcmmo_experience, factions_mcmmo_skills.
This is what i have so far but it doesn't work:
$sql = ("SELECT a.id,
(SELECT COUNT(*) FROM factions_mcmmo_experience WHERE user_id = a.id) as TotalXP,
(SELECT COUNT(*) FROM factions_mcmmo_skills WHERE user_id = a.id) as TotalLevel
FROM (SELECT DISTINCT id FROM factions_mcmmo_users) a LIMIT 10;");
Any help would be very appreciated
EDIT: I have it working now but i'm unsure if its the most efficient way to do things so if anyone could help me out if theres a better way, it would mean a lot.
I would also like to know if it's possible to display the total exp and level with commas if the number is in the thousands for example: total level 5,882 and total xp 582,882
EDIT 2:
I have figured out how to format the numbers but still don't know if my code is efficient
$sql = ("SELECT id, user,
(SELECT FORMAT(Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy),0) FROM factions_mcmmo_skills b WHERE b.user_id = a.id) as TotalLevel,
(SELECT FORMAT(Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy),0) FROM factions_mcmmo_experience c WHERE c.user_id = a.id) as TotalXP
FROM (SELECT id, user FROM factions_mcmmo_users) a group by id ORDER BY TotalLevel DESC, TotalXP DESC LIMIT 10;");
EDIT 3
Updated code from scaisEdge but was displaying everyones level as 1 and XP as 1, so i changed count(*) changed to sum, added an order By TotalLevel in Descending order and that seems to have worked but i can't get it to display the persons name (user column) in the user table? not sure if i was supposed to change to sum because it didn't work the other way.
$sql = ("SELECT a.id, b.TotalXP, c.TotalLevel
FROM (SELECT DISTINCT id FROM factions_mcmmo_users) a
INNER JOIN (
SELECT user_id, Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy) as TotalXP
FROM factions_mcmmo_experience
GROUP By user_id
) b on b.user_id = a.id
INNER JOIN (
SELECT user_id, Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy) as TotalLevel
FROM factions_mcmmo_skills
GROUP by user_id
) c on c.user_id = a.id
ORDER BY TotalLevel DESC
LIMIT 10;");
EDIT 4
Everything working but when i try to format the totals using "FORMAT(Sum(Columns), 0) on the inner joins, the EXP Total appears to work but the main Total Level is not displaying results that are over 1,000 and it breaks the leaderboard positioning, it should be sorting them on total level but it appears to be random, when u remove the format,0 it goes back to working
I would like it to display commas if the number number is the thousands for example: Total Level: 5,532 and Total EXP 5882,882
See live demo: http://mcbuffalo.com/playground/leaderboards/server/factions-mcmmo.php
Updated Code trying to use Format:
$sql = ("SELECT a.id, a.user, b.TotalXP, c.TotalLevel
FROM (SELECT id, user FROM factions_mcmmo_users) a
INNER JOIN (
SELECT user_id, FORMAT(Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy), 0) as TotalXP
FROM factions_mcmmo_experience
GROUP By user_id
) b on b.user_id = a.id
INNER JOIN (
SELECT user_id, FORMAT(Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy), 0) as TotalLevel
FROM factions_mcmmo_skills
GROUP by user_id
) c on c.user_id = a.id
ORDER BY TotalLevel DESC;");
EDIT 5
Changed number with PHP, everything works
Original Images
you could use an couple of inner join
$sql = ("SELECT a.id, a.name, b.TotalXP, c.TotalLevel
FROM (SELECT DISTINCT id, name FROM factions_mcmmo_users) a
INNER JOIN (
SELECT user_id, COUNT(*) as TotalXP
FROM factions_mcmmo_experience
GROUP By user_id
) b on b.user_id = a.id
INNER JOIN (
SELECT user_id, COUNT(*) as TotalLevel
FROM factions_mcmmo_skills
GROUP by user_id
) c on c.user_id = a.id
LIMIT 10

How to join another table?

Right now I'm using UNION to get records from multiple tables, which is fine. But I want to include the author for the specific post.
$run = mysql_query("
SELECT article_id AS id, title, smalldesc, hits, coverpic AS picture, timestamp, member_id AS mid, type FROM articles
UNION
SELECT video_id AS id, titel, smalldesc, hits, ytid AS picture, timestamp, member_id AS mid, type FROM videos
UNION
SELECT picture_id AS id, title, smalldesc, hits, coverpic AS picture, timestamp, member_id AS mid, type FROM pictures ORDER BY timestamp DESC LIMIT ".$postnumbers." OFFSET ".$offset."
") or die(mysql_error());
I want the following select to be a part of the code above:
SELECT member_id, picture, fname, lname FROM members WHERE member_id='mid'
I want to get the member from each post, so I can print out who made the post.
You've got, as you asked, to join the members table to the three part queries of the UNION:
SELECT
a.article_id AS id,
a.title,
a.smalldesc,
a.hits,
a.coverpic AS picture,
a.timestamp,
a.member_id AS mid,
a.type,
m.picture,
m.fname,
m.lname
FROM
articles a
INNER JOIN
members m
ON
a.member_id = m.member_id
UNION
SELECT
v.video_id,
v.titel,
v.smalldesc,
v.hits,
v.ytid AS picture,
v.timestamp,
v.member_id AS mid,
v.type
m2.picture,
m2.fname,
m2.lname
FROM
videos v
INNER JOIN
members m2
ON
v.member_id = m2.member_id
UNION
...
to get this information.

Fetch friend details from table help needed

Here is my table structure (fun_users)
id first_name last_name email passkey place profession self_des profile_img user_type active last_login reg_date reported_banned
And my friendship table is
id user_id friend_id status date_request from_ip
And here is the query im using to fetch details of logged in user friend
SELECT `fun_friends`.`id` as fid, `fun_users`.`id` as uid, `fun_users`.`first_name`, `fun_users`.`profile_img`, `fun_users`.`profession`, `fun_users`.`place` FROM (`fun_friends`) JOIN `fun_users` ON `fun_users`.`id`=`fun_friends`.`friend_id` WHERE (`fun_friends`.user_id= '".$_SESSION['user_row_id']."' AND `fun_friends`.`status` =1) OR (`fun_friends`.friend_id= '".$_SESSION['user_row_id']."' AND `fun_friends`.`status` =1)
The result is
fid uid first_name profile_img profession place
11 47 Agnii thumbs/2013-03-311364721555.jpg Software engineer somewhere
The query returns the details of loggedin user not his friend details. can anyone help me ?
The query below uses a subquery which gets all the friends for specific user. Table fun_users is joined against the subquery twice because there are two columns on the subquery which are dependent on it.
SELECT a.id AS FID,
IF(a.user_ID = 'user_row_id_HERE', c.id, b.id) AS UID,
IF(a.user_ID = 'user_row_id_HERE', c.first_name, b.first_name) AS first_name,
IF(a.user_ID = 'user_row_id_HERE', c.last_name, b.last_name) AS last_name,
IF(a.user_ID = 'user_row_id_HERE', c.profile_img, b.profile_img) AS profile_img,
IF(a.user_ID = 'user_row_id_HERE', c.profession, b.profession) AS profession,
IF(a.user_ID = 'user_row_id_HERE', c.place, b.place) AS place
FROM
(
SELECT id, user_ID, friend_ID
FROM friendship
WHERE 'user_row_id_HERE' IN (user_ID, friend_ID) AND
status = 1
) a
INNER JOIN fun_users b
ON a.user_ID = b.id
INNER JOIN fun_users c
ON a.friend_ID = c.ID
So the question arises, what happens on this line?
IF(a.user_ID = 'user_row_id_HERE', c.id, b.id) AS UID
Basically, it test for the value of the user_ID from the subquery if it is equal to the current user. If it happens to be equal, the column from table fun_users c will be returned and vice versa.
To further gain more knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins

Categories