I am trying to insert list of items from dev.test1 table, but I am struggling with logic ...
Face following problems:
Before insert statements I would like to add "if not exists" - select content in dev.qa_postmetas
f.URL which I am getting in second query is not coming from correct row in dev.test1 - If want to select f.URL where f.title = b.title
Query:
INSERT INTO dev.qa_posts (type, categoryid, userid, created, title, content, tags)
(SELECT 'Q_QUEUED', '1', '3', NOW(), f.title, f.img, f.tagsv
FROM dev.test1 f)
LIMIT 1;
INSERT INTO dev.qa_postmetas (postid, title, content)
(select MAX(b.postid) , 'qa_q_extra',f.URL
from dev.qa_posts b
left JOIN dev.test1 as f on b.postid = f.id)
LIMIT 1 ;
Any assistance will be appreciated
To avoid emty records try IS NULL function in MySQL.
Second query you join to another one and limiting insertion to one.
You may have more results from joined query then you attemt to insert.
Debug your second join select to check what results you have.
Take out limitation to insert all records from joined queries.
Is that what you mean?
Related
I am trying to only show unique userIds (userIds are (0,1,2,3,4,5,6,7,8,9 etc...) for the query I am running. I tried using DISTINCT in my query, but it only shows me unique values of the rows that have 2 or more of the same userId.
Is there a way I can use php to only show the unique values. My weak points are arrays and it makes it more complicated because its using data from a MySQLi query.
Example right now I have with the query now (lets say its GROUP BY rentPaid DESC and the rent total is 800.00 for all users):
userID rentPaid rentMonth
2--------800.00------April
1--------500.00------April
3--------400.00------April
3--------400.00------April
1--------200.00------April
1--------100.00------April
Example desired output:
userID rentPaid rentMonth
2--------800.00------April
1--------500.00------April
3--------400.00------April
Can I do this with MYSQL because I tried DISTINCT and it wouldn't work, how about PHP?
Query:
SELECT
properties.*,
leases.*,
users.userId, users.primaryPhone,
CONCAT(users.userFirstName,' ',users.userLastName) AS user,
admins.adminName, payments.*
FROM
properties
LEFT JOIN leases ON properties.propertyId = leases.propertyId
LEFT JOIN assigned ON properties.propertyId = assigned.propertyId
LEFT JOIN admins ON assigned.adminId = admins.adminId
LEFT JOIN users ON properties.propertyId = users.propertyId
LEFT JOIN payments ON properties.propertyId = payments.propertyId
WHERE
payments.rentMonth = '$currentMonth' AND
payments.rentYear = '$currentYear'
Edit: Please excuse my formatting, this is my first post.
Edit: Added query....its long, but works lol. I only want unique userIds (no double or triple userIds etc...)
I suspect this is what you want:
SELECT userID, MAX(rentPaid) AS maxRentPaid, rentMonth
FROM yourTable
WHERE rentMonth = "April"
GROUP BY userID
ORDER BY maxRentPaid
I'm trying to do a left join using two tables, where I need to get all user id and name in first which satisfies a condition and total number of rows in the second table for each user. If a user doesn't have a row in the second table, it must be null or zero.
This is my eloquent query.
$users->where('users.access_type', '=', 'type1')->orwhere('users.access_type', '=', 'type2')
->leftJoin(DB::raw("(SELECT user_id, COUNT(*) as count FROM table2 WHERE date > '2014-09-17 16:30:04' GROUP BY user_id) temp_table"), function($leftJoin) {
$leftJoin->on('temp_table.user_id', '=', 'users.user_id');
})->select(DB::raw('users.user_id, users.name, temp_table.count as count'))->orderBy('count')->get();
which doesn't returns the user with null count value. instead it returns the user with least count. I printed the query log and copied the raw query for the above query, filled the values and executed. which works perfectly and also returns the user with null entries. No changes made to the query obtained from query log other than adding the values. Copying the raw query below.
select users.user_id, users.name, temp_table.count as count from `users` left join (SELECT user_id, COUNT(*) as count FROM table2 WHERE date > '2014-09-17 16:30:04' GROUP BY user_id) temp_table on `temp_table`.`user_id` = `users`.`user_id` where `users`.`access_type` = 'type1' or `users`.`access_type` = 'type2' order by `count` asc
I have tried changing the column name of the user_id field for both using as user. Also tries replacing null values with zero using IFNULL. But still no go. Please let me know what am I doing wrong.
In your Eloquent query, you need to replace the last function call ...->first() by ...->get() in order to retrieve all the results instead of only the first one.
Below is the source table and the output I am trying to achieve.
I would like each another_table.id to only appear once in the output, with subsequent values displaying in new columns
This will give you the output, given the table in your question. With CTEs instead of subqueries for added clarity...
with intials as(
SELECT id,
another_table.id as another_table_id,
value as field_1
FROM
main_table
WHEN
variable.id = 1),
finals as(
SELECT id,
another_table.id as another_table_id,
value as field_1
FROM
main_table
WHEN
variable.id = 2)
SELECT
initials.id,
initials.another_table_id
initials.value field_1,
finals.value field_2
FROM
initials
LEFT OUTER JOIN
finals on initials.another_table_id = finals.another_table_id;
Before asking this question, I already search a lot of entries on Google and StockOverflow. Nothing can fulfil my question.
There are two tables - group_sale_bonuses and members. I want to check is already there records with product_id "1" in the group_sale_bonuses.
If not, I want to insert all records from members table into group_sale_bonuses with product_id "1".
My overall requirement is as follow:
IF ((Select count(id) from group_sale_bonuses where product_id = 1) = 0) THEN
INSERT INTO group_sale_bonuses (member_id, product_id, quantity_counter, credit)
SELECT id, 1, 0, 0 FROM members
END IF
But this sql causes the errors.
I know there are solutions about Insert Ignore, Where Not Exists.
But these conditions checking are based on per each record. I have thousands of records in members table. I want to make condition checking just one time like in my above sql example.
By the way, I will use this Sql in Php web application.
You could just set the code in a WHERE clause instead of the IF.
INSERT INTO group_sale_bonuses(
member_id,
product_id,
quantity_counter,
credit)
SELECT
id, 1, 0, 0 FROM members
WHERE(
SELECT
count(id) FROM group_sale_bonuses
WHERE product_id = 1
) = 0;
This should do it for all product_id's
SELECT m.product_id, m.member_id FROM members AS m
LEFT JOIN group_sale_bonuses AS gsb ON gsb.product_id = m.product_id
WHERE gsb.product_id IS NULL ;
You can filter it to a specific product_id by adding to the where clause
SELECT m.product_id, m.member_id FROM members AS m
LEFT JOIN group_sale_bonuses AS gsb ON gsb.product_id = m.product_id
WHERE gsb.product_id IS NULL AND m.product_id = 1;
Take a look at this SQLfiddle: http://sqlfiddle.com/#!2/8482c/2
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 [.....]