How can i get one table id values to another table - php

I have a two tables in my database. One is "blog" second is "comment".
Blog table have this structure
id, title, text, writer_id, created_at, updated_at
Comment table have this structure
id, blog_id, text, commenter_id, created_at, updated_at
I want to get id value from blog table as in comment table in the form of blog_id . How can i get the same value.
Example:
One blog posted. blog table have these values.
id: 1
title: hi i m blogger
text: how are you
writer_id: 5 (same User id)
created_at:25 feb
updated_at: 25 feb
Blog posted . One commenter comes and comment on this post. Value should be comes as like this in comment table
id=1
blog_id:1
text: ok i know
created_at:25 feb
updated_at: 25 feb
id of blog table and blog_id of comment table should be same. How can i do this with query or php code?.

Try This Query
SELECT b.id, c.`text`,..... FROM blog b
LEFT JOIN comment c
ON b.id = c.blog_id
ORDER BY commenter_id DESC ;
if you want for perticular blog so add WHERE CONDITION
SELECT b.id, c.`text`,.... FROM blog b
LEFT JOIN comment c
ON b.id = c.blog_id
b.id = 'Your ID'
ORDER BY commenter_id DESC ;

First of all you have to put foreign constraint that the value of column "Blog_Id" in table comment should always be from table "blog"
select * from blog bg inner join comment cm on cm.blog_id = blog.id this is the query for retrieving what you want.

Related

PHP/MySQL - COUNT 2 different totals within 1 Table for each User

I can't get my head around this one!! So I'm seeking help....
For each user I'm trying to sum the types of posts assigned to them.
User Table: crm_users
Columns: users_id, users_first, users_last
Posts Table: crm_entities
Columns: crm_id, users_id, settype, post
I would like to COUNT() the total posts for a user where settype=draft as well as settype=published, for example:
Name------------Published---------Drafts
John Smith---------15---------------3
Nancy Grace--------11------------- 5
Jay Martin----------7--------------14
I am sure I am making this more difficult than it probably is... or at least I think !
Thanks for any advice!
Because MySQL uses 1 as representation for true and 0 for false, you could use:
SELECT
u.users_first,
u.users_last,
SUM(p.settype='published') as Published,
SUM(p.settype='draft') as Drafts
FROM
crem_users u
LEFT JOIN
crm_entities p
ON
u.users_id = p.users_id
GROUP BY
u.users_id
ORDER BY Published DESC;
Try:
select u.users_first, (select count(*) as qty from crm_entities e where e.settype='draft' and e.users_id = u.users_id) drafts, (select count(*) as qty from crm_entities e where e.settype='published' and e.users_id = u.users_id) published from crm_users u

Query to order the relevant data in different table

There is two table: user, comments
The structure is like this:
user
-----
id
name
comments
--------
id
title
user_id
comments_id
Notice that the comments_id is the parent ID of that comment record, that means, if comments_id is null, it is a POST, if it is not null, it is a REPLY.
So I would like to select them and ordering like this
Post 1
Reply 1 for Post 1
Reply 2 for Post 1
Post2
...
And here is the codeigniter query I have attempt, I also need the user table for getting the user name
$this->db->select('c.id as id, u.name as username, c.txtMsg as txtMsg, c.createDate as createDate, c.updateDate as updateDate, c.imageURL as imageURL, c.postID as postID');
$this->db->from('comment as c, user as u');
$this->db->where('u.id = c.userID');
$this->db->order_by('c.id', $order_type);
How to construct the query to order the list? Thanks for helping.

How to COUNT the number of rows where a column matches a column of another table

I want to display the number of posts a user has made, but I have a few different tables and need to match ids and count them.
Something like this:
Users Table
userid username email regdate
34 mister email#some.tld 2013-10-26 12:01:07
Posts Table
postid creator post_comment post_title status
1 34 This is comment Post 1 published
2 12 This is comment Post 2 published
3 34 This is comment Post 3 pending
4 25 This is comment Post 4 published
5 34 This is comment Post 5 published
Now I already have a query where I select all data about a particular user from the users table:
mysqli_query($conn, "SELECT * FROM users WHERE userid = $userid");
$userid is the id of user that's currently logged in. And this works fine: it selects all relevant information about that user.
But I want to display the number of posts each user makes. I read somewhere on w3schools the SQL COUNT function works something like this:
mysqli_query($conn, "SELECT COUNT(creator) AS userposts FROM posts WHERE creator=$userid");
However, as you can see in table example posted, out of 5 posts, 3 are from user 34 and 1 of these 3 is not published.
I don't know how to make a SQL query that selects all users where userid matches $userid and then selects creator and status from posts and counts the number of posts where creator is $userid and status is published.
This is the output I'm ultimately aiming for:
User mister have 2 posts published.
In order to get only the number of published posts, you should refactor your condition statement by ANDing status = 'published'
mysqli_query($conn, "SELECT COUNT(creator) AS num_posts FROM posts
WHERE creator=$userid AND status = 'published'");
SELECT COUNT(creator) AS userposts FROM posts p
LEFT JOIN users u ON p.creator=u.userid
WHERE creator=$userid AND status='published'
As you asked in the comment, all in one query:
SELECT users.*, COUNT(creator) AS userposts FROM users u
LEFT JOIN posts p ON p.creator = u.userid
WHERE p.creator = $userid AND p.status = 'published'

MYSQL Select Statement with IN Clause and Multiple Conditions

There might be an easy solution here, but it seems to have me tripped up. I'm trying to query a table based on an array of values in two columns. Here is the pertinent table structure and sample data
comment table
id, userId, articleId .... etc etc
article table
id, userId .... etc etc
Data: UserIds = 3, 10. ArticleIds = 1, 2
Let's say I'm trying to find all the comments for a particular set of article IDs: 1,2
I can easily use this query
select * from comments WHERE articleId IN(1,2)
However, here is where it gets complex. I have a query that executes prior to the comments query that determines the appropriate article IDs. Those IDs are in an array. Also in an array are the corresponding user IDs for each article.
What I want to do now is query the comments table for only the articles in the array (1,2) AND only for those comments made by the original author (3, 10).
The simple query above will bring back all the comments for articleId 1 and 20. So for example I can't figure out where to add another conditional that says onyl comments for articleId 1, 20 AND corresponding userId, 3, 10.
Any help or suggestions would be much appreciated!
I think the simplest way is to write:
SELECT comments.*
FROM articles
JOIN comments
ON articles.id = comments.articleId
AND articles.userId = comments.userId
WHERE articles.id IN (1, 2)
;
The AND articles.userId = comments.userId clause is what enforces your "only for those comments made by the original author" requirement.
Alternatively, you can use an EXISTS clause:
SELECT *
FROM comments
WHERE articleId IN (1, 2)
AND EXISTS
( SELECT 1
FROM articles
WHERE id = comments.articleId
AND userId = comments.userId
)
;
or a single-row subquery:
SELECT *
FROM comments
WHERE articleId IN (1, 2)
AND userId =
( SELECT userId
FROM articles
WHERE id = comments.articleId
)
;
Have you tried just
select * from comments WHERE articleId IN(1,2) and authorId in (3,10)
If not, please update your question why it's so.
You can add as many IN statements as you want:
select * from comments WHERE articleId IN(1,2) AND userId IN (3,10)
Can't you just make the query that runs first a subquery within your stated query:
SELECT * FROM `comments` WHERE `articleId` IN(1,2) AND `userId` IN (__subquery__)
-- you can use subquery
select * from comments WHERE articleId IN(1,2)
and userId in ( select userId from article where id in (1,2) )

How to select a column value as a column name and group the results as a row

How do I select a column value as a column name and group the results as a row.
I have a table as such:
id articleId label value
1 1 title Example title
2 1 description This is the description
3 1 author Me
4 2 title Example of another type of article
5 2 description Short description
6 2 author Someone else
Is it possible to select all of the rows and use the label as the column name and the value as the value of that column name and then group them by the article name.
So how I would like to have it returned:
articleId title description author
1 Example title This is the.. Me
2 Example of an.. Short descr.. Someone else
I'm using this for a CMS where the user can define the fields for an article so we don't have to customize the table's. This is why i'm not making the tables as the I would like to have it returned. I am also aware that I can just as easily convert the result to this in php.
-- edit --
Can this be done without knowing what labels are added? In this example im using title, description and author. But it could very well be something totally different like title, shortDescription, availableTo, techInformation, etc.. The idea is that the article's are customizable for the user without needing to change the database and query's
I figured I'd better post as an answer, even if not what OP would like to hear. What you are asking to do is to populate a query with a variable number of columns based on the distinct values within column label, all associated with articleID. Taking your specific example, the following would be the resultant query that I would most likely go to in this instance (though the example from #Devart is equally valid)
SELECT
t.id,
t.articleId,
t1.value AS title,
t2.value AS description,
t3.value AS author
FROM `tableName` t
LEFT JOIN `tablename` t1
ON t1.article_id = t.article_id AND t1.label = 'title'
LEFT JOIN `tablename` t2
ON t2.article_id = t.article_id AND t2.label = 'description'
LEFT JOIN `tablename` t3
ON t3.article_id = t.article_id AND t3.label = 'author'
Now expanding this to account for up to n labels, we get the following query (metacode included, this query will NOT execute verbatim)
SELECT DISTINCT label FROM `tableName`;
SELECT
t.id,
t.articleId
// for (i=1;i<= number of distinct labels) {
,t[i].value AS [value[i]]
// }
FROM `tableName` t
// for (i=1;i<= number of distinct labels) {
LEFT JOIN `tablename` t[i]
ON t[i].article_id = t.article_id AND t[i].label = [value[i]]
// }
;
So what you can do is one of the following.
SELECT t.* FROM tablename t and then have PHP process it as required
SELECT DISTINCT label FROM tablename and have PHP build the second query with the many LEFT JOINs (or MAX / GROUP BY logic if preferred)
Create a Stored Procedure to do the same as #2. This would most likely be more efficient than #2 however may be less efficient overall than #1.
You can use pivote table trick -
SELECT
articleId,
MAX(IF(label = 'title', value, NULL)) AS title,
MAX(IF(label = 'description', value, NULL)) AS description,
MAX(IF(label = 'author', value, NULL)) AS author
FROM
table
GROUP BY
articleId
Try below :
select t1.articleId,t1.title,t1.description,t1.author
from tablename as t1
left join (select max(articleId) as articleId
from tablename
group by articleId ) as t2
on t1.articleId=tsm.articleId where [.....]

Categories