Mysql query, select join two table - php

I have a LIKE table and a BOOK table and my user_id.
I want to pull only i have liked from BOOK table with BOOK NAMES and AUTHOR
My json will:
{book_id:1,bookname:sample,author:sean,user_id:111}
tables
-----------BOOK TABLE------------
ID ---- BOOK AUTHOR ---- BOOK NAME
1
2
...................................
USERS TABLE
ID-------NAME
1
2
.............
LIKE TABLE---------------------------
ID-----BOOK ID-------LIKER USER ID---
1
2
.....................................

$stmt = $mysqli->prepare("SELECT book.*, users.*, like.* FROM like INNER JOIN
users ON like.liker_user_id = users.id INNER JOIN
book ON like.book_id = book.id WHERE
users.id = ?
");
$stmt->bind_param( "d", $user_id);
$stmt->execute();
$stmt->bind_result($col1);
// then fetch and close the statement

For getting all the data related to likes you can run this sql command.
The result set you can loop and generate the JSON.
Make sure in the query you have all your column names correctly given.
select
b.book_id,
b.bookname,
b.author,
u.user_id
from
`like` l
inner join book b on b.book_id = l.book_id
inner join users u on u.user_id = l.user_id
If you need to filter data just add a where condition after the last JOIN as
where u.user_id = {your user id}

Related

Sum values from a SQL table to a value from other SQL table

I have a PHP page like this:
ID
Name
Hours Flown
1
Joao
7
2
Andre
10
3
Tiago
15
And I want that "Hours Flown" column show a value from one column from a SQL table (users) with a sum of another SQL table (flights) where ID matches the "users" table.
I have a while($row = $result_list_pilots->fetch_assoc()) to show the table if that helps...
SQL query for now is a bit simple "SELECT * FROM users ORDER BY name;". Already tried some JOIN examples but without success as the imported_hours gets duplicated as result from flights table is being found.
Tables:
[Tables]
How to do this?
I think here is what you want :
SELECT
u.ID
, u.Name
, SUM(ISNULL(f.HoursFlown,0)) + MAX(Imported_hours) 'Hours Flown'
FROM Users u
LEFT JOIN Flights f
ON u.ID = f.User_id -- or whatever the fk is
GROUP BY u.ID, u.Name
SELECT u.ID, u.Name, SUM(f.HoursFlown)
FROM Users u
INNER JOIN Flights f ON u.Name = f.Name
GROUP BY u.ID, u.Name

What Sql Join can I use to combine my three tables

I made a query that user can see all the post of active users but not of those inactive, but also they should not see the post of users they blocked or blocked them how can I do that?, the block_users table has block_by_userid and blocked_userid column.
I tried INNER JOIN the post table with members table which every inactive users post cannot be seen anymore., How will I combine the block_users table?
$GetPost = "SELECT Post.* FROM Post
INNER JOIN Members ON Post.Poster_user_id = Members.User_id
WHERE Status='active'";
you might try FULL OUTER JOIN
the idea it to get all items in both tables member and block_users and then filter the data using where clause, i am sorry if i miss using the fields name , so please check the tables names, i assume block_users.block_by_userid contained the blocked user id if not use the correct field
$GetPost = "SELECT Post.* FROM Post
INNER JOIN Members ON Post.Poster_user_id = Members.User_id
FULL OUTER JOIN block_users ON Members.User_id = block_users.user_id
WHERE Status='active'
AND
WHERE block_users.block_by_userid != Members.User_id";
Suppose I am doing this for a user xyz whose user_id is 123 then below is a query which will return expected output for user 123.
Query:
SELECT Post.* FROM Post
INNER JOIN Members ON Post.Poster_user_id = Members.User_id
WHERE Status='active' and post.poster_user_id NOT IN(select block_by_userid from block_users where blocked_user_id = 123 UNION select blocked_user_id from block_users where block_by_userid = 123)

Query Two Databases at once using Prepared statements

I have function called getData($Books, $Users, $InputID); that receives two database connections and User ID.
On the User Database, I have a table called Users
-----------------
UserID | UserName
-----------------
On the Books Database, I have a table called Books
------------------------------
BookID | BookName | BookUserID
------------------------------
What I want to do is to write ONE query that will:
Select the the User on the Users table with UserID = $InputID, and also select the book on Books Table where BookUserID = $InputID;
This must be done using a Prepared Statement..
This is what i have tried.
function getData($Books, $Users, $InputID){
$fetch_results = prepare('SELECT * from UsersDB.Users U LEFT JOIN BooksDB.Books B ON B.BookUserID = U.UserID Where UserID = :InputID');
$fetch_results->execute(array(':userID' => $InputID));
return $Data;
}
if your both DB(UserDb, BooksDB) on same server then query will be like.
SELECT u.UserName, b.BookName
FROM UserDB.dbo.Users u
INNER JOIN BooksDB.dbo.Books b
ON b.UserId = b.BookUserId
WHERE u.UserId = $InputID
OR BookUserID = $InputID;
If your both DB(UserDB, BooksDB) on different server then.
First you need to create link for other server then fire the following like query with link name, Let your link Name is LinkServer2 and you are firing query from server1.UserDB. Make sure to use fully qualified name for linked server.
SELECT u.UserName, b.BookName
FROM UserDB.dbo.Users u
INNER JOIN LinkServer2.BooksDB.dbo.Books b
ON b.UserId = b.BookUserId
WHERE u.UserId = $InputID
OR BookUserID = $InputID;
if you want to use LEFT JOIN and retrieve all number of columns(SELECT *) then you can do it no problem.

Queries from Diffrent Tables How to Join Suggest PLease (PHP)(SQL)

I need help regarding JOIN tables to get category name & author name from other tables.
for articles site I have Three Tables
articles
categories
users
Articles Table structure :
id
title
slug
content
category
author
date
I save category ID & user ID in articles table with each article
While Displaying Articles for a category I use this:
(just some draft idea not full code)
localhost/testsite/category.php?cat=category-slug
$catslug = ($_GET["cat"]);
//GET CAT ID from category table from slug
$qry = "SELECT * from category WHERE slug='$catslug';
$res = mysql_query($qry) or die("Error in Query");
$ans = mysql_fetch_array($res);
$cid = $ans['id'];
$catname = $ans['title'];
<h2><?php echo $catname; ?></h2>
//after getting cat-id query to get article of that ID
$aqry = select * from article where category=$cid ORDER BY date";
$ares = mysql_query($aqry) or die("Error in Query");
$aans = mysql_fetch_array($ares))
$aid = $aans['author'];
//then another query to get author name from users
select username from users where id=$aid
I m learning PHP & not much familiar with JOIN statement & combining queries
need help/suggestions hw can I achieve same with JOIN tables instead of different queries to get catname and author name from tables.
Thanks
This should do what you want
SELECT distinct c.title, U.Username
from category C join article A on A.category=C.id
join users U on U.id=A.author
WHERE C.slug= :catslug
Assuming Category id is foreign jey in article table
Try this query
select username from users
where id in (
select author from category cat
inner join article art
on cat.category_id =art.category_id
where cat.slug= $cat
order by art.date desc )
$q = "SELECT article.*
FROM article
LEFT JOIN category
ON article.category = category.ID
LEFT JOIN users
ON article.author = users.ID
WHERE article.slug = :slug";
:slug is where you would insert (bind if you're using PDO) $_GET['slug']
You can do some different thing with a SQL request. You can do some join in your SQL request but you can also do another SELECT statement in your request Like
SELECT SOMETHINGS FROM A_TABLE WHERE (SELECT ANOTHER_THING FROM ANOTHER_TABLE WHERE VALUE =1
But this statement will only work if you have 1 result in your second request
If you want to join two table with some value, you'll have to do it like this
SELECT something FROM a_table AS alias1 JOIN another_table AS alias2
ON alias1.value1 = alias2.value1 and .....
You can compare all the value that you want from one table to another and you can also join more than two table and the ON key word is not requested by sql syntax you can just do
SELECT * FROM table_1 join table_2
and it will show you all thje data from two table but be sure that this is the data you want this kind of little query can have some big result and slow down your app
you can read more there http://dev.mysql.com/doc/refman/5.0/en/join.html
First off, you should write a stored proc... but here's how you would get articles by categoryID that includes both the category name and user name.
Given the following table structures:
article
---------
articleID <- primary key
title
slug
content
categoryID <- foreign key
userID <- foreign key
createdDT
category
--------
categoryID <- primary key
categoryName
user
--------
userID <- primary key
userName
Here's how to write the query using joins:
SELECT a.title, a.slug, a.content, a.createdDT, c.categoryName, u.userName
FROM dbo.article a
JOIN dbo.category c on a.categoryID = c.categoryID
JOIN dbo.user u on a.userID = u.userID
WHERE a.categoryID = #categoryID
Here's an article from Microsoft on JOINs - http://msdn.microsoft.com/en-us/library/ms191517.aspx

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

Categories