mysql join when field are table name and primary key - php

I have to build a complex query on SugarCRMfor a report. SugarCRM relationship it's stored on some tables, so I need to join multiple tables using the relationship tables. The tables have a model and model_id which identify a table and record primary id.
Below is an example of what I am trying to do.
BLOGS : Main table with field ID
BLOG_ENTRY : Child table of Blog with with field ID, BLOG_ID (FK of BLOGS table) and POST_CONTENT_ID (FK of next table BLOG_CONTENT)
BLOG_CONTENT with field ID, MODEL (which identify a child table) and MODEL_ID (which identify child table id)
BLOG_CONTENT_TABLE_ONE with field id
Suppose we can have more than one table BLOG_CONTENT_TABLE_TWO, ...
The query should be something like:
select blogs.id, blog_content.model, blog_content.model_id, blog_content_table_one.id
from blogs, blog_entry, blog_content, blog_content_table_one
where
# join blog and blog_entry
blog.id = blog_entry.blog_id
# join blog_entry and blog_content
AND blog_entry.content_id = blog_content.id
# join blog_content and blog_content_table_one
AND blog_content.model = 'blog_content_table_one'
AND blog_content.model_id = blog_content_table_one.id
This works, but if there is more table, I suppose I should use a MySQL case ?

First, use the ON clause for JOINs. Second, I don't think it's possible to get all possible combinations, but for three blog content tables, you could go for something like this.
SELECT
blogs.id,
blog_content.model,
blog_content.model_id,
blog_content_table_one.id
blog_content_table_two.id
blog_content_table_three.id
FROM blogs
JOIN blog_entry
ON blog.id = blog_entry.blog_id
JOIN blog_content
ON blog_entry.content_id = blog_content.id
LEFT JOIN $blogtable1 blog_content_table_one
ON blog_content.model_id = blog_content_table_one.id
AND blog_content.model = '$blogtable1'
LEFT JOIN $blogtable2 blog_content_table_two
ON blog_content.model_id = blog_content_table_two.id
AND blog_content.model = '$blogtable2'
LEFT JOIN $blogtable3 blog_content_table_three
ON blog_content.model_id = blog_content_table_three.id
AND blog_content.model = '$blogtable3'
WHERE blog_content.model IN ('$blogtable1', '$blogtable2', '$blogtable3')

Related

How to replace two user id columns with names?

I have a table with two columns.
created_by | assigned_to
One is the person who create a "to do card", the other column is the person who is assigned to do it.
The columns are filled with id, for example; (1,2,3).
My question is how can i replace this id with the names that are saved in another table.
by far this is what i got.
SELECT tickets.*, users.Name, users.LastName
FROM tickets
LEFT JOIN users ON tickets.assigned_to = users.uid
AND tickets.id_usuario = users.uid
but when i try to print the name of the persona
Created by: <?= query['Name']; ?>
Assigned to: <?= query['Name']; ?>
but i got the same name in both columns.
Your current query only joins to users when the creator and assigned-to user ID are the same.
You'll need to join to your users table twice to retrieve the separate records. You do this by adding more joins...
SELECT
c_users.Name as created_by_name,
c_users.LastName as created_by_last_name,
a_users.Name as assigned_to_name,
a_users.LastName as assigned_to_last_name
FROM tickets t
INNER JOIN users c_users
ON t.created_by = c_users.uid
-- or t.id_usuario = c_users.uid, it is not clear from your question
INNER JOIN users a_users
ON t.assigned_to = a_users.uid
I've used INNER JOIN instead of LEFT JOIN as it doesn't seem feasible that you'd have broken relationships between the two tables.

Query one table, to get name from another table

I have 3 tables in my database, Categories,Subcategories and Articles.
My Articles table contains columns caled CategoryID and SubcategoryID, which are foreign keys of the table Categories and Subcategories.
My question is, how can I get the name of the Category and Subcategory stored only as ID's in my Articles Table.
I think I need a kind of subquery or join.
Here is what I have:
SELECT ArticleTitle
,CategoryID
,SubcategoryID
FROM Articles
WHERE SubcategoryID =
(SELECT SubcategoryName
FROM Subcategories
WHERE SubcategoryName = 'info'
)
When I execute this code in mysql, there are no erros, but I receive 0 results. All tables are containing some data.
change this:
where SubcategoryID = (select SubcategoryName from Subcategories
to this
where SubcategoryID in (select SubcategoryID from Subcategories
the changes were
the equal sign is now the word in.
the subquery is selecting SubcategoryID instead of SubCategoryName
Using Joins :
SELECT a.ArticleTitle AS ArticleTitle,
c.CategoryName AS CategoryName,s.SubcategoryName AS SubcategoryName
FROM
Articles a JOIN Categories c on a.CategoryID=c.ID JOIN Subcategories s on a.SubcategoryID=s.ID
WHERE s.SubcategoryName = 'info';

mySQL JOIN on one to many

I have multiple tables that are linked together on the search page. They are currently queried like this:
SELECT * FROM tripreportentries
JOIN tripreport ON tripreportentries.reportid = tripreport.tripreportid
JOIN user_details on tripreportentries.userid = user_details.userid
WHERE TripEntryHeading LIKE '%%' AND tripreportentries.ispublic = 1
ORDER BY tripreportentryid
I have since created a new table called tripphotos with the table columns named:
tripphotoid
reportid
entryid
photoname
The issue is each entry can have more than one corresponding photo in the photo table.
I am looking to find a way to JOIN the new table to the statement above but not return several rows for each entry id.
Any ideas on how to join this table?
EDIT - I also want to just tie one image to the returned row and not all of them just so I can show the image as a thumbnail on the browse page
I normally would list every column and group by the non aggregates, but mySQL will allow this I believe; given the mySQL group by extensions; and we expect the tripReport and user_Details columns to be the same for each joined photoname.
SELECT tripReport.*, user_details.*, max(photoname) as maxPhotoPerReport
FROM tripreportentries
JOIN tripreport ON tripreportentries.reportid = tripreport.tripreportid
JOIN user_details ON tripreportentries.userid = user_details.userid
JOIN tripphotos ON tripreportentries.reportid = tripPhotos.ReportID
WHERE TripEntryHeading LIKE '%%' AND tripreportentries.ispublic = 1
GROUP BY ReportId
ORDER BY tripreportentryid
or we could do this using an inline view to get the max photo for each report and then join that set to your base query.
SELECT *
FROM tripreportentries
JOIN tripreport ON tripreportentries.reportid = tripreport.tripreportid
JOIN user_details on tripreportentries.userid = user_details.userid
JOIN (SELECT max(photoName) as MaxPhotoPerReport, ReportID
FROM TripPhotos
GROUP BY ReportID) B
ON B.ReportID = tripReport.ReportId
WHERE TripEntryHeading LIKE '%%' AND tripreportentries.ispublic = 1
ORDER BY tripreportentryid

mySQL Return field names from multiple foreign keys

I'm new to mySQL and was hoping to get some help. I have a table layed out in the following way:
TASK
task_id *
tasktype_id (FK)
proj_id (FK)
empl_id (FK)
taskstat_id (FK)
hrs
notes
If I do a query like this, the results print out fine but the numeric references to foreign keys are printed.
SELECT * AS task FROM task
INNER JOIN tasktype ON tasktype.tasktype_id = task.tasktype_id
WHERE taskstat_id = 1";
But I would like to print out the field names instead of field numbers for the foreign keys in the resulting table. Any ideas? This is what I tried, but without any luck.
SELECT task.task_id,
tasktype.tasktype_id,
project.proj_id,
employee.empl_id,
taskstatus.taskstat_id,
task.hrs,
task.note
FROM task, tasktype, project, employee, taskstatus
INNER JOIN tasktype ON tasktype.tasktype_id = task.tasktype_id
WHERE task.taskstat_id = 1";
well, assuming the "field name" in the related tables (column name) is called... name (I don't know the structure of your joined tables)
select t.task_id,
tt.name, //or tt.description, or whatever
p.name, //same
e.name, //same
ts.name, //same
t.hrs,
t.note
FROM task t
inner join tasktype tt on tt.tasktype_id = t.tasktype_id
inner join project p on p.proj_id = t.proj_id
inner join employee e on e.empl_id = t.empl_id
inner join taskstatus ts on ts.taskstat_id = t.taskstat_id
where t.taskstat_id = 1

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