Matching IDs in two different tables - php

I have two tables; NEWS and CATEGORIES. In the NEWS table, there is CatID field which matches with CatID table in the categories. I get the categoryID with the following code but I want to the category name of the news, not the ID. How can I pull it from the categories table?
<?php
$SQL = mysql_query("SELECT * FROM News WHERE Active = 1 ORDER BY DateEntered DESC");
while ( $Result = mysql_fetch_array($SQL)) {
$CatID[] = $Result[CatID];
$NewsName[] = $Result[NewsName];
$NewsShortDesc[] = $Result[NewsShortDesc];
}
?>
<div class="toparticle">
<span class="section"><?=$CatID[0] ?> </span>
<span class="headline"><?=$NewsName[0] ?></span>
<p><?=$NewsShortDesc[0] ?></p>
</div>

You can change your SQL query to include an inner join to get the name. To illustrate, I'm going to make the assumption that the category name column in the 'CATEGORIES' table is called 'CatName.' You can use this query:
SELECT n.*, c.CatName FROM News n
INNER JOIN Categories c ON n.CatID = c.CatID
WHERE Active = 1
ORDER BY DateEntered ASC

By what I've understood, maybe you want to do:
SELECT name FROM CATEGORIES as c, NEWS as n WHERE c.CatID = n.CatID AND n.CatID = 123
I'm a bit rusty in SQL, I think it's something like this.
From what I've understood from your question, you want to do something like this.

In the following I create 2 table for news and categories :
Table News
id| cat_id | title
1 | 1 | Test
Table Categories
id | name
1 | Horror
u can select name of category use OUTER JOIN like this
SELECT news.*, categories.name AS category_name FROM news
LEFT JOIN categories ON categories.id= news.cat_id;
if u want to know more about this outer join

Related

MYSQL - SELECT products WHERE parent_category is active

assuming we have a database category structure like this
# Categories Table
| category_id | parent_category_id | status |
# Products Table
| product_id | category_id |
how do i get the list of products in a category only if the parent_category_id has an active status = 1 ?
i guess i could use some sub-query in the SELECT statement, but i don't know how! :(
something like:
SELECT p.*, (SELECT * FROM ? WHERE ? ) AS x
FROM products AS p
LEFT JOIN categories AS c ON p.category_id = c.category_id
WHERE ...
AND p.product_id = '?'
AND ...
Thank you in advance for any advice!
NB: i'm using PHP as backend language, just in case i need some sort
of data manipulation to pass to the mysql query.
try not to use subquery, because it can affect the speed of loading data
maybe it can help
SELECT *
FROM categories c
INNER JOIN products p ON p.category_id=c.category_id
WHERE c.status = 1
Here a example query, I don't use left join or join, becasue you require that the record exists in order to get the status.
SELECT
*
FROM
products, categories
WHERE
products.category_id = categories.category_id
AND status = '1'
SELECT p.* FROM products p
INNER JOIN categories child ON child.category_id = p.category_id
INNER JOIN categories parent ON parent.category_id = child.parent_category_id
WHERE parent.status=1
First you have to get all active categories
SELECT child.*
FROM Categories child
JOIN Categories parent
ON child.parent_category_id = parent.category_id
AND parent.status = 1
But you also need the root categories with not parent_id
SELECT *
FROM Categories
WHERE parent_category_id IS NULL
AND status = 1
So you UNION both
SELECT *
FROM Categories child
JOIN Categories parent
ON child.parent_category_id = parent.category_id
AND parent.status = 1
UNION ALL
SELECT *
FROM Categories
WHERE parent_category_id IS NULL
AND status = 1
Now you get the products for those categories
SELECT *
FROM ( ... UNION ALL ... ) active_categories
JOIN Products
ON active_categories.category_id = Product.category_id

Join three rows with one row from another table

I am working on a home project. In my database I have two table called movies and category. in the movies table there are three rows named category,category_two,category_three. And in the category table there are only one row name category_name.
I wanted to join all three rows from the movies table with the row named category_table from category table.
but I do not know how to do that query.
Please help me.
This is how you should do it:
movies table
------------
id
name
categories table
----------------
id
name
movie_categories table
----------------------
movie_id
category_id
Like this you can have any amount of categories for a movie. Then to get a specific movie along with its categories you can do:
select m.*, c.name as category_name
from movies m
left join movie_categories mc on m.id = mc.movie_id
left join categories c on c.id = mc.category_id
where m.name = 'star wars'

Mysql user subscription query fails

I have a database named socialnetwork and has 5 tables category , post_category , posts , subscribe , user.
my table structures
-------- -------------
category posts
-------- ------------
categoryID postID
categoryName post
userID
categoryID
-------------- ---------------
post_category subscribe
--------------- ---------------
postID subscriberID
categoryID categoryID
--------------
usertable
--------------
userID
userName
data's in the table
category table usertable
-------------------------- -------------------
categoryID categoryName userID userName
--------------------------- --------------------
1 film 1 jijojohn32
2 television 2 sijojohn
posts_category table subscribe table
------------------ -------------------------
postID categoryID subscriberID categoryID
--------------------- ------------------------
1 1 1 1
1 2 1 2
2 2 2 2
posts table
---------------------------------------------------
postID post userID categoryID
--------------------------------------------------
1 this post is cool 1 1
2 demo post 2 2
User 1 can subscribe to different categories and he can see the articles in the categories he subscribes. That's what i am trying to implement here. And i have this query but it's not giving me the result i want.
USE socialnetwork;
SELECT socialnetwork.usertable.userName,socialnetwork.posts.post, GROUP_CONCAT(socialnetwork.category.categoryName) as category
FROM socialnetwork.category
INNER JOIN subscribe
ON subscribe.categoryID = category.categoryID
INNER JOIN posts
ON posts.categoryID = subscribe.categoryID
INNER JOIN usertable
ON usertable.userID = posts.userID
INNER JOIN socialnetwork.post_category
ON post_category.postID = posts.postID
WHERE subscriberID = "1"
GROUP BY socialnetwork.category.categoryName
Here's the result i am getting
---------------------------------
username post category
----------------------------------
jijojohn32 this post is cool film, film
sijojohn demo post television
The result i want
---------------------------------------------
username post category
-------------------------------------------
jijojohn32 this post is cool film,television
sijojohn demo post television
I want the post from the categories he subscribed to , the username of the user posted the articles , and categories which posts reside. What's wrong in my query ?. any idea ?. thanks
You are not aggregating by the right columns. I think this is the query that you want:
SELECT ut.userName, p.post, GROUP_CONCAT(c.categoryName) as category
FROM socialnetwork.category c INNER JOIN
subscribe s
ON s.categoryID = c.categoryID INNER JOIN
posts p
ON p.categoryID = s.categoryID INNER JOIN
usertable ut
ON ut.userID = p.userID INNER JOIN
socialnetwork.post_category pc
ON pc.postID = p.postID
WHERE subscriberID = 1
GROUP BY ut.userName, p.post;
Here's the working query. I made some modifications in the table. Deleted the categoryID from posts. Made a new table called post_category.
--------------
post_category
-------------
postID
categoryID
Here's the query
SELECT GROUP_CONCAT(category.categoryName) as category , category.categoryID , subscribe.subscriberID , posts.post ,
usertable.userName
from category
INNER JOIN subscribe
ON subscribe.categoryID = category.categoryID
INNER JOIN post_category
ON category.categoryID = post_category.categoryID
INNER JOIN posts
ON posts.postID = post_category.postID
INNER JOIN usertable
ON usertable.userID = posts.userID
WHERE subscriberID = 1
GROUP BY post_category.postID
There exists a conflict
Category table consists of
Category id and Category Name
Post Table consists of
Post id and Corresponding Category Id
As well as
Post_Category table consists of
Post id and Category Id
Hence it is picking from the Posts table, that
Row 1 - has only 1 category id associated with it
I suggest you remove Category id from Posttable
It is pointless to have 2 keys in 1 table, and similar 2 keys in other table.
Try to establish Primary key Foreign key relationship.
Hope that helps

How to Select Category Name on the Basis of Id

I am Using PHP, MYSQL. I have two tables
Table posts with following fields
id,
title,
body,
cat_id
Table categories with following fields
cat_id,
cat_name
Suppose, I have Following Data in posts table
id = 1
title = "This is Test Post"
body = "This is the Body of Test Pots"
cat_id = 3
and in categories table
cat_id = 3
cat_name = "Mobiles"
If I Use the Following SQL Statement
"SELECT * FROM posts WHERE id=1";
It will give me following output
id = 1
title = "This is Test Post"
body = "This is the Body of Test Pots"
cat_id = 3
But I Want the Following Output
id = 1
title = "This is Test Post"
body = "This is the Body of Test Pots"
cat_id = Mobiles
How can I get the above mentioned output.
Note: I know some kind of JOIN is used in this kind of situation, But I don't know how to use it. One More thing, Is it possible to get my desired output without using any JOIN, because I heard that JOINs Effect the Efficiency. If JOIN is necessary Please tell me the most efficient Way to get my desired output.
SELECT * FROM posts JOIN categories USING (cat_id) WHERE posts.id = 1
It's possible to achieve the same using a correlated subquery instead (however this is likely to be less efficient than a join):
SELECT *, (SELECT cat_name FROM categories WHERE cat_id = posts.cat_id)
FROM posts
WHERE id = 1
You have to use join querty to join posts and categories in order to get informations from both tables. So you try with the following query
SELECT t1.*,t2.cat_name FROM posts as t1 join categories as t2 on t1.cat_id = t2.cat_id WHERE t1.id=1
Use join query
try this
SELECT id, title, body, cat_name FROM posts
join categories on posts.cat_id = categories.cat_id WHERE id=1
SELECT post.id, post.title, post.body, cat.cat_name from posts inner
join categories cat on cat.cat_id = post.cat_id
and post.id = 1
I think you have to learn JOINS first read this articles
JOINS
JOINS VS SUB-QUERY
now about your question checkout the
SQL FIDDLE
SELECT * FROM posts As p
JOIN categories AS c ON c.id = p.cat_id
WHERE p.id = 1
now its your choice whether to use Joins or Sub-Queries both have its pros and cons
thus select as per your requirement.
hope this will help you ...!

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

Categories